5

I have tried the code below: the purpose is to generate a dictionary where each key has a list as a value. The first iteration goes well and generates the item as I want it, but the second loop, the nested for loop, doesn't generate the list as expected.

Please help me with this simple code. There must be something wrong with it, the code is as below:

 schop = [1, 3, 1, 5, 6, 2, 1, 4, 3, 5, 6, 6, 2, 2, 3, 4, 4, 5]
 mop =   [1, 1, 2, 1, 1, 1, 3, 1, 2, 2, 2, 3, 2, 3, 3, 2, 3, 3]
 mlist = ["1","2","3"]
 wmlist=zip(mop,schop)

 title ={}
 for m in mlist:
     m = int(m)
     k=[]
     for a,b in wmlist:
         if a == m:
            k.append(b)
     title[m]=k
 print(title)

The results are like:

title: {1: [1, 3, 5, 6, 2, 4], 2: [], 3: []}

Why do the second key and the third key have an empty list?

Thanks!

pushkin
  • 9,575
  • 15
  • 51
  • 95
Pepin Peng
  • 457
  • 1
  • 8
  • 21

2 Answers2

7

Your code would have worked as you expect in Python 2, where zip creates a list of tuples.

In Python 3, zip is an iterator. Once you iterate over it, it gets exhausted, so your second and third for loops won't have anything left to iterate over.

The simplest solution here would be to create a list from the iterator:

wmlist = list(zip(mop,schop))
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • One can also replace `for a, b in wmlist:` directly with `for a, b in zip(mop, schop):`, and not create an intermediate list. –  Mar 11 '18 at 00:15
-1

i think that the best thing that you have to consider is the version of python that you have installed. This is the output that i obtained with your code in python2: enter image description here

{1: [1, 3, 5, 6, 2, 4], 2: [1, 3, 5, 6, 2, 4], 3: [1, 6, 2, 3, 4, 5]}

But with Python3 this is the answer that i obtained:

enter image description here

{1: [1, 3, 5, 6, 2, 4], 2: [], 3: []}

If you are sure that you have the properly vesion, only you have to consider the indentation that you have in your code. Good luck!!