Remap Mysql tuple to dictionary

Fredrik Lundh fredrik at pythonware.com
Mon Sep 25 12:36:15 EDT 2006


Pom wrote:

> I want to convert a Mysql resulset to a dictionary.

that is, you want to convert an array of (key, value, ...) tuples to a
dictionary containing key: (value, ...) pairs, right ?

> I made some code myself, and want to ask you if I do this the right way.
> 
> def remapmysql(a):
>      return (a[0], (a[1:]))
> 
> def test_map():
>      count = 100000 # count of simulated records
>      l1 = range(0, count)
>      l2 = range(count , 2 * count )
>      l3 = range(2 * count, 3 * count )
>      z1 = zip(l1, l2, l3) # simulate a mysql resultset
> 
>      d1 = dict(map(remapmysql,z1))
> 
>      return d1

looks fine to me.

if you care about performance, and is using a recent Python, you could 
try doing

    d1 = dict((row[0], row[1:]) for row in z1)

instead, and see if that runs faster (this uses a generator expression 
instead of a callback and a full list).

</F>




More information about the Python-list mailing list