Faster (smarter?) dictionary building

Tim Peters tim.one at comcast.net
Thu Oct 30 14:57:25 EST 2003


[Michael T. Babcock]
> I have a list of column headings and an array of values:
> headings, values = ['a', 'b', 'c'], [1, 2, 3]
>
> I want to construct a dictionary such that d['a'] = 1 and so on.
>
> The first way I tried to do this was:
>
> d = {}
> for h,v in headings, values:
>     d[h] = v
>
> It turns out this doesn't work, but it was worth a try.  I ended up
> falling back on the more C-like:
>
> for i in range(len(headings)):
>     d[h[i]] = v[i]
>
> Is there anything somewhat cleaner or more pythonesque I could do
> instead?

In sufficiently recent versions of Python (>= 2.2),

>>> headings, values = ['a', 'b', 'c'], [1, 2, 3]
>>> dict(zip(headings, values))
{'a': 1, 'c': 3, 'b': 2}
>>>

Looking at the value of the anonymous nested expression should make it
clearer at first:

>>> zip(headings, values)
[('a', 1), ('b', 2), ('c', 3)]
>>>

Picture a zipper, then squint <wink>.






More information about the Python-list mailing list