Making a dict from two lists/tuples

Fredrik Lundh fredrik at pythonware.com
Thu May 24 11:41:54 EDT 2001


Andrew:
> I want a neat way to turn
>
> keys = ('foo', 'bar')
> values = (1, 2)
>
> into
>
> dict = {'foo': 1, 'bar': 2}.

Jonas:
> >
> > > for key,value in keys,values
> > >     dict[key] = value
> >
> > Bzzzt! Wrong answer.
>
> Why is it wrong??

did you try it?

>>> keys = ('foo', 'bar')
>>> values = (1, 2)
>>> dict = {}
>>> for key, value in keys, values:
...     dict[key] = value
...
>>> assert dict == {'foo': 1, 'bar': 2}
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError
>>> dict
{'foo': 'bar', 1: 2}

> And what is zip supposed to do, i'm trying it here on another machine,
> which gives me a NameError(1.6 Linux)

it's a 2.0 thing:

>>> print zip.__doc__
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences.  The returned list is truncated
in length to the length of the shortest argument sequence.

Cheers /F





More information about the Python-list mailing list