Making a dict from two lists/tuples

Alex Martelli aleaxit at yahoo.com
Thu May 24 12:54:01 CEST 2001


"Andrew Stribblehill" <a.d.stribblehill at durham.ac.uk> wrote in message
news:87u22bw197.fsf at womble.dur.ac.uk...
>
> I want a neat way to turn
>
> keys = ('foo', 'bar')
> values = (1, 2)
>
> into
>
> dict = {'foo': 1, 'bar': 2}.
>
> I'm sure there's some (possibly-functional) idiom to do this in one
> simple line, but I'm totally unable to work out what!

As I suggested in a followup, but just to complete and clarify:
    dict = {}
    map(dict.setdefault, keys, values)
seems a reasonable way to do it.

I will confess that I, personally, would tend to use the alternative,
"less neat" (but more likely to be understandable by a reader who
still hasn't had his or her morning coffee...)
    dict = {}
    for k, v in zip(keys, values):
        dict[k] = v

However...:

import time

keys = range(10000)
vals = range(10000)

start = time.clock()
d1 = {}
for k, v in zip(keys, vals):
    d1[k] = v
stend = time.clock()

print "Plain:", stend-start

start = time.clock()
d1 = {}
map(d1.setdefault, keys, vals)
stend = time.clock()

print "Fancy:", stend-start


D:\Python21>python po.py
Plain: 0.12956698978
Fancy: 0.0406777842777

D:\Python21>python po.py
Plain: 0.126390609312
Fancy: 0.0406811366581


The fancy/neat form seems to be better than
three times faster on my box, so it may be
worth using DESPITE its fanciness...:-).


Alex






More information about the Python-list mailing list