Faster (smarter?) dictionary building

Javier Ruere javier_ruere at HotPOP.com
Thu Oct 30 22:44:26 EST 2003


Michael T. Babcock wrote:

> 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?  Thanks.
>
How about this:

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


Javier







More information about the Python-list mailing list