Converting tuples to dictionaries?

David Bolen db3l at fitlinxx.com
Wed Sep 26 16:44:39 EDT 2001


"Mart van de Wege" <mvdwege.usenet at drebbelstraat20.dyndns.org> writes:

> Hmmm. Remember I started this thread with asking how to get my SQL
> query results into dictionaries? I found a few methods called
> dictfetch* in psycopg (the DB module for Postgresql). I was just
> wondering on how to use those, but I can't find them in the docs.

I don't use psycopg, but if I recall your original post you also
mentioned just writing the conversion loop yourself, and I'd consider
that a very viable solution.

While there are some other modules out there that wrap SQL queries
into higher level objects that provide dictionary and sequence like
access (Greg Stein's dtuple.py for example), it's pretty straight
forward (and by no means "wrong") to just handle it yourself.

For example, here's a small function I use that takes a supplied
DB-API complaint cursor, executes a fetchall() operation on it, and
then returns a list of dictionaries for each retrieved row, where the
dictionary on each row can be indexed by field name:

    def QueryToDictList(cursor):
	"""QueryToDictList(cursor)

	Execute query on the supplied cursor and return the result as a
        list of dictionaries, using the cursor description as the keys in
        each dict"""

	result = []
	rows = cursor.fetchall()
	for currow in rows:
	    rowdict = {}
	    for curcol in range(0,len(cursor.description)):
		rowdict[cursor.description[curcol][0]] = currow[curcol]
	    result.append(rowdict)

	return result


--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list