I have a list of dictionaries in python. I want to update one key:value pair for all the dicts with unique values but instead all of them are getting the same value.
Here's my code:
num_cntxts=4
pkt_eop =[{'type' : 'eop', 'number':1}]
pkt_eop_pattern = pkt_eop*num_cntxts
#I want to add a 'cntxt' key to each of the 4 dicts
#which should have the value as the list position
for i,pkt_eop_inst in enumerate(pkt_eop_pattern):
print i,pkt_eop_inst
pkt_eop_inst['cntxt']=i
>0 {'cntxt': 0, 'type': 'eop', 'number': 1}
1 {'cntxt': 2, 'type': 'eop', 'number': 1}
2 {'cntxt': 4, 'type': 'eop', 'number': 1}
3 {'cntxt': 6, 'type': 'eop', 'number': 1}
The print statement shows the individual dict elements but the result is:
>pkt_eop_pattern
'[{'cntxt': 6, 'type': 'eop', 'number': 1}, {'cntxt': 6, 'type': 'eop', 'number': 1}, {'cntxt': 6, 'type': 'eop', 'number': 1}, {'cntxt': 6, 'type': 'eop', 'number': 1}]
What I wanted was the pkt_eop_pattern to match the print output:
>pkt_eop_pattern
'[{'cntxt': 0, 'type': 'eop', 'number': 1}, {'cntxt': 2, 'type': 'eop', 'number': 1}, {'cntxt': 4, 'type': 'eop', 'number': 1}, {'cntxt': 6, 'type': 'eop', 'number': 1}]
When I iterate over the list, I expected to get a pointer to each dict. However, that is not the case since all elements are taking the value of the last iteration.