Python. converting 2 lists into one dictionary object
11,059
Solution 1
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)}
Solution 2
keys = ['one', 'two', 'three']
values = [1, 2, 3]
dict(zip(keys, values))
this is already the most pythonic way.
You can use a dict comprehension, if you really must:
{k: v for k,v in zip(keys, values)}
Solution 3
dict(zip(list1, list2))
is probably the best way to do it. Don't use comprehensions, that's a silly requirement.
Related videos on Youtube
Author by
Fred4106
Updated on June 04, 2022Comments
-
Fred4106 almost 2 years
Possible Duplicate:
Map two lists into a dictionary in PythonI 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.
-
Ben Burns over 11 yearsWhy do you have to use comprehension?
-
abarnert over 11 yearsIt's not an exact duplicate, because "The catch is that I have to use comprehension". The accepted answer uses
dict(zip(keys, values))
; there is no answer that uses a list comprehension (although one answer uses a generator expression that could be turned into a comprehension with just two character changes.) That may be a stupid requirement, but it is a requirement, so it's not a duplicate.
-
-
DSM over 11 yearsTo be fair, the OP didn't say "list comprehension", so
d={k:v for k,v in zip(a, b)}
might qualify. (Of coursedict(zip(keys, values))
is how I would do it too.) -
phihag over 11 years@DSM Great point, added to the answer.
-
root over 11 years@ user1718234 -- You are welcome. If it was helpful you should accept the answer.