-1

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'}

user3843763
  • 259
  • 2
  • 5

3 Answers3

0

You can zip() the lists first and then pass it to dict():

>>> dict(zip(List1, List2))
{'a': '0', 'c': '2', 'b': '1', 'd': '3'}
Mitul Shah
  • 1,556
  • 1
  • 12
  • 34
0

Try

>>> dict(zip(List1, List2))
Nilesh
  • 20,521
  • 16
  • 92
  • 148
0

Using dict comprehension

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'}
Jan Vlcinsky
  • 42,725
  • 12
  • 101
  • 98
  • Thank you for your help. What I have to do If i have to display each key-value pair in a new line. – user3843763 Jul 18 '14 at 10:32
  • @user3843763 If you need a string with this format, then using list comprehension (dict does not apply here) is: `" ".join("'" + key + "':'" + val + "'" for key, val in zip(List1, List2))` – Jan Vlcinsky Jul 18 '14 at 10:34