Making a dict from two lists/tuples

Alex Martelli aleaxit at
Thu May 24 06:54:01 EDT 2001

"Andrew Stribblehill" <a.d.stribblehill at> wrote in message
news:87u22bw197.fsf at
> 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


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

Plain: 0.12956698978
Fancy: 0.0406777842777

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...:-).


More information about the Python-list mailing list