Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. converting 2 lists into one dictionary object [duplicate]

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.

like image 606
Fred4106 Avatar asked Jan 23 '26 17:01

Fred4106


1 Answers

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)}
like image 155
root Avatar answered Jan 25 '26 05:01

root



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!