Reputation: 97
I want keys to repeat the same way in each dictionary. I.e. start from A and go till E. But it seems itertools.cycle is skipping one every time it cycles over. I also want the values to follow the order in the list (i.e. start from 1 in the first dictionary and end with 15 in the last dictionary). Please see code below:
import itertools
allKeys=['A','B','C','D','E']
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
g=itertools.cycle(allKeys)
b=[]
for i in range(3):
dishDict=dict(zip(g,a))
b.append(dishDict)
b
Generates:
[{'A': 11, 'B': 12, 'C': 13, 'D': 14, 'E': 15},
{'B': 11, 'C': 12, 'D': 13, 'E': 14, 'A': 15},
{'C': 11, 'D': 12, 'E': 13, 'A': 14, 'B': 15}]
As you see, keys in the second dictionary start from B (instead of A, as I would like). Also the values are the same in all three dictionaries in the list.
This is what I want the output to look like:
[{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5},
{'A': 6, 'B': 7, 'C': 8, 'D': 9, 'E': 10},
{'A': 11, 'B': 12, 'C': 13, 'D': 14, 'E': 15}]
I'd really appreciate it if someone could shed some light on what's happening and what I should do to fix it. I have already spent quite a bit of time to solve it myself and also checked the documentation on itertools.cycle. But haven't been able to figure it out yet.
Upvotes: 2
Views: 421
Reputation: 195438
For the required output, you don't need cycle()
:
allKeys=['A','B','C','D','E']
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
it = iter(a)
b=[]
for i in range(3):
dishDict=dict(zip(allKeys,it))
b.append(dishDict)
print(b)
Prints:
[{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5},
{'A': 6, 'B': 7, 'C': 8, 'D': 9, 'E': 10},
{'A': 11, 'B': 12, 'C': 13, 'D': 14, 'E': 15}]
Upvotes: 2