[Tutor] tutorial for dbapi 2.0 how to use data
Roeland Rengelink
roeland.rengelink at chello.nl
Sat May 15 06:13:14 EDT 2004
John Fabiani wrote:
> Hi,
> mycur=con.cursor()
> mycur.execute("select * from sosord")
> mydata=mycur.fetchmany(10)
>
> The above works and returns data. But know I need to understand how
> to view the data. Maybe there is a way to convert the returned list
> into a dictionary. A dictionary would allow me to get information by
> key (the field name). Anyway, is there some paper or tutorial I can
> read on how to view the return data?
The returned items of the list mydata already behave as a dictionary (in
pyPgSQL). I.e:
>>> item = mydata[0] # get the first row from the resultset
>>> item.keys() # show the column names
['a', 'b']
>>> item.values() # show the data in the row
0, 123.5
>>> item['a'] # access as dictionary
0
Incidently, the returned object also worksa a list of values:
>>> for val item:
... print val
...
0
123.5
>>> print item[1]
123.5
Finally, you can access the values as attributes, e.g.:
>>> item.a
0
>>> item.b
123.5
If you want to turn it into a real dictionary, this should work:
>>> d = dict(zip(item.keys(), item.values())
Hope this helps,
Roeland
More information about the Tutor
mailing list