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!
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With