Possible Duplicate:
Map two lists into a dictionary in Python
I have 2 lists like this: ['one', 'two', 'three'] and [1, 2, 3]
I want to turn it into a dictionary like this {'one':1, 'two':2, 'three':3}
The catch is that i have to use comprehension. Thanks.
keys=['one', 'two', 'three']
values= [1, 2, 3]
dictionary = dict(zip(keys, values))
>>> print dictionary
{'one': 1, 'two': 2, 'three': 3}
Take a look at builtin functions, they often become handy. You can use dict comprehensions from Python 2.7 up, but the they should not be the way to do it:
{k: v for k, v in zip(keys, values)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With