Using enumerate loop to update a list of dicts in python not working as expected -



Using enumerate loop to update a list of dicts in python not working as expected -

this question has reply here:

python list of lists, changes reflected across sublists unexpectedly 7 answers

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 together '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 lastly 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 together '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'] =

python list dictionary

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -