Converting tuples to dictionaries?

Mart van de Wege mvdwege.usenet at
Sat Sep 22 21:54:23 CEST 2001

In <mailman.1001021063.1689.python-list at>, Ignacio Vazquez-Abrams

> On Thu, 20 Sep 2001, Mart van de Wege wrote:
>> I have some data in an SQL database. Now AFAICT psycopg (aka pythonDB 2.0 for
>> PostgreSQL) returns the query results as a list of tuples. The data that
>> returns from my query would fit very well in a dictionary, ie. tuple[0] would
>> be the key, and the rest would make the value (or list of values), in fact
>> the conceptual model I have for my program would *need* a dictionary to
>> process.
>> Now the obvious way to turn a list of tuples into a dictionary would be to
>> loop over the list and convert them by assigning tuple[0] to be the key and
>> the rest of the tuple the value. Slightly more efficient would be to define a
>> function that does that with one tuple and then map the function on the list.
>> The question is, is this really the only way to go about that, or am I
>> barking up the wrong tree entirely? It really seems like a brute force
>> approach to me. Is there an alternative?
> No, you pretty much hit the nail on the head:
> ---
> tup=(
>   (1, 2, 3),
>   (4, 5, 6),
>   (7, 8, 9)
> ) 
> dict={}
> def convtuple(t):
>   return {t[0]:t[1:]}
> filter(dict.update, map(convtuple, tup))
> print dict
> ---

Thank you (and Simon too of course), that will help me a lot. Expect me back
soon with more Python/PostgreSQL questions :)
BTW, I'm having a hard time finding an API description for the Python-DB API
2.0. I guess I'll have to start digging through the source? Thankfully it is
mostly self-documenting.


Requiem aeternam dona eis, Domine, et lux perpetua luceat eis.
Requiescant in pace.

More information about the Python-list mailing list