Converting tuples to dictionaries?
Mart van de Wege
mvdwege.usenet at drebbelstraat20.dyndns.org
Thu Sep 27 04:23:26 EDT 2001
In <ulmj1d6mg.fsf at ctwd0143.fitlinxx.com>, David Bolen wrote:
> "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
>
Yep,
That was what I had in mind. Thanks for validating my ideas, and thanks for the
code, that makes everything a lot clearer. I'll go building my utility routines
now, my friends will like that. I'm not very good at keeping a paper
administration, so having some programming skills I'd like my computer to do
the hard work, and I won't mess up my campaign by forgetting mundane details.
Thanks again for the help,
Mart
--
Requiem aeternam dona eis, Domine, et lux perpetua luceat eis.
Requiescant in pace.
Amen.
More information about the Python-list
mailing list