Reputation: 5878
Consider I have the two following tuples:
keys=("second", "minute", "hour", "day")
values=(1, 60, 60, 24)
I would like to create a dictionary that has the keys
tuple as keys and the values
tuple as values. Here's my naive way of doing it:
d={}
for i in xrange(len(keys)):
d[keys[i]] = values[i]
Is there an easier more elegant way of doing this?
I work primarily with Python2.7, so I would prefer the answers to privilege this version.
Upvotes: 2
Views: 449
Reputation: 375854
The zip
function turns a pair of iterables into a list of pairs. The dict
constructor accepts a number of forms of arguments, one of which is a sequence of (key, value) pairs. Put the two together, and you get just what you want:
dict(zip(keys, values))
Upvotes: 7
Reputation: 133664
>>> keys=("second", "minute", "hour", "day")
>>> values=(1, 60, 60, 24)
>>> dict(zip(keys,values))
{'second': 1, 'hour': 60, 'minute': 60, 'day': 24}
Upvotes: 8