12

I have these lists:

list1 = ["a","b","c"]
list2 = ["1","2","3"]

I need to add them to a dictionary, where list1 is the key and list2 is the value.

I wrote this code:

d = {}
for i in list1:
    for j in list2:
        d[i] = j
print d

The output is this:

{'a':'3','b':'3','c':'3'}

What's wrong with this code? How can I write it so the output is

{'a':'1','b':'2','c':'3'}

Thanks!

Aei
  • 677
  • 6
  • 11
  • 17
  • The problem is that `j` is not dependent upon `i` - the nested loops are effectively a cross-apply where only the *last* value is kept. Compare with `for x in range(len(list1)): i = list1[x]; j = list2[x];` - *now* there is a dependency established. However, see the answers nice approaches to establish a dependency. –  Nov 05 '12 at 04:09
  • @user1692740: you should accept the answer which is helpful you, this will help you in getting more answers in future... – avasal Nov 05 '12 at 05:01

4 Answers4

21

Zip the lists and use a dict comprehension :

{i: j for i, j in zip(a, b)}

Or, even easier, just use dict() :

dict(zip(a, b))

You should keep it simple, so the last solution is the best, but I kept the dict comprehension example to show how it could be done.

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
4

you are almost there, except you need to iterate over the lists simultaneously

In [1]: list1 = ["a","b","c"]

In [2]: list2 = ["1","2","3"]

In [3]: d = {}

In [4]: for i, j in zip(list1, list2):
   ...:     d[i] = j
   ...:

In [5]: print d
{'a': '1', 'c': '3', 'b': '2'}
avasal
  • 14,350
  • 4
  • 31
  • 47
  • Thanks! This is exactly what I needed. Only, I'm not extremely versed in Python. What does "zip" do? – Aei Nov 05 '12 at 04:09
  • zip(list1, list2) will give you a list of tuples like `[('a', '1'), ('b', '2'), ('c', '3')]` to work with, for more details you can have a look at http://docs.python.org/2/library/functions.html#zip – avasal Nov 05 '12 at 04:10
1

You can also use dict comprehension to do the following in a nice one-liner.

d = {i : j for i, j in zip(list1, list2)}
Marwan Alsabbagh
  • 25,364
  • 9
  • 55
  • 65
0
list1 = ["a","b","c"]                                                  
list2 = ["1","2","3"]                                                                                                                        
mydict = {}                                                            
for i,j in zip(list1,list2):                                           
   mydict[i] = j                                                      
print mydict   
Brian Cajes
  • 3,274
  • 3
  • 21
  • 22