Faster (smarter?) dictionary building

M

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] = v

Is there anything somewhat cleaner or more pythonesque I could do
instead? Thanks.
 
D

David Eppstein

"Michael T. Babcock said:
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))
 
B

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top