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.
--
Michael T. Babcock
C.T.O., FibreSpeed Ltd.
http://www.fibrespeed.net/~mbabcock
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>.
> 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.
d = dict(zip(headings,values))
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
How about:
>>> headings, values = ['a', 'b', 'c'], [1, 2, 3]
>>> d = {}
>>> for h, v in zip(headings, values):
... d[h] = v
...
>>> d
{'a':1, 'c':3, 'b':2}
Jay
>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
IMO it would be interesting to make that work, but spelling it like a tuple unpacking
assignment with a 'for' in front of it, to make it step through the sequences on the right. E.g,
d = {}
for h,v = headings, values: # illegal now, proposed lazy parallel sequence unpacking
d[h] = v
would work as "expected", i.e., as if
for h,v in itertools.izip(headings,values):
d[h] = v
Regards,
Bengt Richter
> 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
Beautiful; thank-you very much. I was sure my code looked uglier than
necessary.