Making a dict from two lists/tuples

Alex Martelli aleaxit at yahoo.com
Thu May 24 06:46:33 EDT 2001


"Jonas Meyer Rasmussen" <meyer at kampsax.dtu.dk> wrote in message
news:9eiljf$jg1$1 at eising.k-net.dk...
> for key,value in keys,values
>     dict[key] = value

Not really what the original poster was asking for:

> "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}.

as witness:

>>> dict={}
>>> keys = ('foo','bar')
>>> values = (1,2)
>>> for key,value in keys,values:
...   dict[key]=value
...
>>> dict
{'foo': 'bar', 1: 2}
>>>

Perhaps you mean:

for key,value in zip(keys,values):
    dict[key] = value

The zip() built-in function is what is generally
suggested for 'parallel' loops over two sequences
(you can do them with map, too, or looping over
indices, but zip exists specifically for this).

But this is not really a "neat way", or, as the
original poster later asks, a "possibly functional"
idiom.  I believe something like:
    map(dict.setdefault, keys, values)
is more likely to be what he had in mind.  There
is a functional difference in case of duplicates
within keys -- the zip-form puts each key in
correspondence with the 'last' value found for
it, while .setdefault uses the 'first' one.


Alex






More information about the Python-list mailing list