Converting tuples to dictionaries?

Ignacio Vazquez-Abrams ignacio at openservices.net
Thu Sep 20 23:23:31 CEST 2001


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
---

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>





More information about the Python-list mailing list