Re: Dictionary

Tim Roberts <[email protected]> Wed, 21 Apr 2010 09:22:47 -0700
Newsgroups gmane.comp.python.db.psycopg.devel
Organization Providenza & Boekelheide, Inc.
Message-ID <[email protected]>
Antonio Prado wrote:
> I'm trying modify just the dictionary.
>
> Psycopg2 returning a list of records and one with the keys.
>   

What you get back is a list of tuples.  Each entry in the list is a
record, and each record is a tuple of field values.  A tuple cannot be
modified.  So, if you need to modify the record locally (and that's not
an uncommon need), then you need to turn the tuple into something else. 
A dictionary is a convenient alternative.

You can do that yourself this overly tricky way:
    desc = cur.description
    row = cur.fetchone()
    row = dict( [ (d[0],f) for (d,f) in zip(desc,row) ] )

Or you can use the DictCursor that's built-in to psycopg2.  Instead of a
list of tuples, it returns a list of dict-like objects, which you can
convert to a dict and then write it.
    import psycopg2
    import psycopg2.extras

    db = psycopg2.connect( ... )
    cur = db.cursor( cursor_factory = psycopg2.extras.DictCursor )
    cur.execute( ... )
    row = dict(rset.fetchone())
    print row['name']
    row['AddMyOwn'] = 123

-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.