I am stuck at some problem. I have two lists in python as
>>> List1 = ['a','b','c','d']
>>> List2 = ['0','1','2','3']
I want to merge these both the lists into a dictionary as
>>> Dictionary = { 'a':'0', 'b':'1', 'c':'2', 'd':'3'}
I am stuck at some problem. I have two lists in python as
>>> List1 = ['a','b','c','d']
>>> List2 = ['0','1','2','3']
I want to merge these both the lists into a dictionary as
>>> Dictionary = { 'a':'0', 'b':'1', 'c':'2', 'd':'3'}
You can zip()
the lists first and then pass it to dict()
:
>>> dict(zip(List1, List2))
{'a': '0', 'c': '2', 'b': '1', 'd': '3'}
Since Python 2.7 there exists dictionary comprehension too.
>>> List1 = ['a','b','c','d']
>>> List2 = ['0','1','2','3']
>>> {key: val for key, val in zip(List1, List2)}
{ 'a':'0', 'b':'1', 'c':'2', 'd':'3'}
The other constructs are more efficient, if you have in your List1
ready key names and in List2
ready values for them.
As soon as you have to calculate them, dict comprehension can be flexible enough to do that in short piece of code.
As sample could be inserting values, which as twice as "big" as what is in List2
>>> {key: val*2 for key, val in zip(List1, List2)}
{ 'a':'00', 'b':'11', 'c':'22', 'd':'33'}