0

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.

peaxol
  • 497
  • 4
  • 13

1 Answers1

1

What happens when you do

pkt_eop_pattern = pkt_eop*num_cntxts

is that you get a list with num_cntxts references to the same dictionary.

You will need to copy the dictionary. Luckily, since you're iterating over it (and list extension is relatively lightweight in python):

num_cntxts=4
pkt_eop   =[{'type' : 'eop', 'number':1}]

#I want to add a 'cntxt' key to each of the 4 dicts
#which should have the value as the list position

for i in xrange(num_cntxts):
   my_copy = pkt_eop.copy()
   pkt_eop_pattern.append(my_copy)
   my_copy['cntxt'] = i
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • Thanks, didnt realize I was getting the references to the same dictionary. This explains it! – peaxol Apr 09 '15 at 21:43