Re: Dictionary

Antonio Prado <antonio-m7WKv7+duuT/[email protected]> Thu, 22 Apr 2010 14:12:50 -0300
Newsgroups gmane.comp.python.db.psycopg.devel
Message-ID <[email protected]>
Em Qua, 2010-04-21 às 09:22 -0700, Tim Roberts escreveu:
> 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
> 

Correct! That's right I'm trying to do.

But I'm having problem bellow.

What is wrong?

[...]
cur = db.cur(cursor_factory=psycopg_extras.DictCursor)
cur.execute("SELECT * FROM users")
result = cur.fetchall()

>>>print result
[[2, 'JOSE ALBERTO', 'MOTA'], [3, 'MARY ANN', 'MARY']]

>>> print resultado[0]['nome']
JOSE ALBERTO

>>> resultado[0]['nome'] = 'teste'
TypeError: list indices must be integers, not str

result = dict(result)
>>ValueError: dictionary update sequence element #0 has length 3; 2 is
required





_______________________________________________
Psycopg mailing list
[email protected]
http://lists.initd.org/mailman/listinfo/psycopg