Using enumerate loop to update a list of dicts in python not working as expected -
this question has answer here:
i have list of dictionaries in python. want update 1 key:value pair dicts unique values instead of them getting same value.
here's code:
num_cntxts=4 pkt_eop =[{'type' : 'eop', 'number':1}] pkt_eop_pattern = pkt_eop*num_cntxts #i want add 'cntxt' key each of 4 dicts #which should have value list position 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} print statement shows individual dict elements 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 wanted pkt_eop_pattern match 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 iterate on list, expected pointer each dict. however, not case since elements taking value of last iteration.
what happens when
pkt_eop_pattern = pkt_eop*num_cntxts
is list num_cntxts
references same dictionary.
you need copy
dictionary. luckily, since you're iterating on (and list extension relatively lightweight in python):
num_cntxts=4 pkt_eop =[{'type' : 'eop', 'number':1}] #i want add 'cntxt' key each of 4 dicts #which should have value list position in xrange(num_cntxts): my_copy = pkt_eop.copy() pkt_eop_pattern.append(my_copy) my_copy['cntxt'] =