Reputation: 61
I have been trying to create a nested dictionary I guess there is something about dictionaries I'm missing. I succeeded in created the values and keys on my console but was getting errors when I tried to append it. It kept giving me the last value in my dictionary. Please what I'm I doing wrong?
u= [(2, 'errorid 4'), (1, 'errorid 4260'), (6, 'errorid 7'), (75, 'errorid 0'),
(1, 'errorid 14'), (4, 'errorid 4b07')]
v=['Frequency', 'Item']
data ={}
dicts ={}
for i,con in enumerate(u):
con = list(con)
for m,n in enumerate(con):
dicts[v[m]]=n
print(dicts)
data[i+1]=dicts
The output on the console for dicts was correct, but when I tried to nest it is was not working:
{'Frequency': 2, 'Item': 'errorid 4'}
{'Frequency': 1, 'Item': 'errorid 4260'}
{'Frequency': 6, 'Item': 'errorid 7'}
{'Frequency': 75, 'Item': 'errorid 0'}
{'Frequency': 1, 'Item': 'errorid 14'}
{'Frequency': 4, 'Item': 'errorid 4b07'}
Output should look like this:
data = {1: {'Frequency': 2, 'Item': 'errorid 4'},
2: {'Frequency': 1, 'Item': 'errorid 4260'},
3: {'Frequency': 6, 'Item': 'errorid 7'}
4: {.... }
Upvotes: 0
Views: 165
Reputation: 71454
Your data
dictionary consists of a bunch of copies of the same dictionary (dicts
), which you keep overwriting. Every time you change the values in dicts
you're implicitly changing the value for all the entries in data
simultaneously.
The comprehension in Jean-Claude's answer will build a new dict for each item, avoiding this problem.
Upvotes: 0
Reputation:
Try this:
data = {i + 1: {p: q for p, q in zip(v, x)} for i, x in enumerate(u)}
Output:
{1: {'Frequency': 2, 'Item': 'errorid 4'}, 2: {'Frequency': 1, 'Item': 'errorid 4260'},
3: {'Frequency': 6, 'Item': 'errorid 7'}, 4: {'Frequency': 75, 'Item': 'errorid 0'},
5: {'Frequency': 1, 'Item': 'errorid 14'}, 6: {'Frequency': 4, 'Item': 'errorid 4b07'}}
Upvotes: 1