[Tutor] Cursors as Dictionaries

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 11 Apr 2001 03:03:33 -0700 (PDT)


On Wed, 11 Apr 2001, Danny Ruttle wrote:

> I understand that the Python DB2 API allows the
> results of a database query to be returned as a
> dictionary.

Can you point out where you saw this?



> I have tried the following:
> 
>  >>> import PgSQL
>  >>> import libpq
>  >>>
>  >>> db_init = PgSQL.connect(database="testdb3")
>  >>> my_cursor = db_init.cursor()
>  >>> my_cursor.execute("select user_id, first_name from ruser")
>  >>> dict = {}
>  >>> dict = my_cursor.fetchall()
> 
> but when I try to access the dictionary I get the following error:
> 
>  >>> h = dict.keys()
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> AttributeError: keys
> 
> On further investigation I discovered that the type of
> dict is now a list!!


SQL fetchall()'s should return back a list of results.  More formally,
they return a sequence of sequences, not a dictionary.



> This isn't what I want - I need the field names as well as the data in the
> result set.

You'll probably need to look at the "description" attribute of your
cursor object, after you do the execute.  According to:

     http://python.org/topics/database/DatabaseAPI-2.0.html

after doing the execute, the database module should automagically fill in
that information so you can take a look at it.



By the way, have you tried working with SQLDict?  This might be a useful
module for you:

    http://dustman.net/andy/python/SQLDict

Dunno how well it works with Postgres, but I hope it comes in handy.