Remap Mysql tuple to dictionary
fredrik at pythonware.com
Mon Sep 25 18:36:15 CEST 2006
> 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, (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
d1 = dict((row, 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).
More information about the Python-list