Item in nested dictionary in a list can't be modified

good day
When adding a dictionary array inside a list I am not able to modify one of the dictionary items, instead all the dictionary items are modified...


#create a dictionary
dcirc={'mode':1,'alarm':4,'step':7}

#append the same dictionary in a list for 3 times
lcirc=[]
for x in range(3):
	lcirc.append(dcirc) 

#modify item 'alarm' from list array 2 
lcirc[2]['alarm']=99

Result: (all the 'alarm' item changes)
[{'mode': 1, 'alarm': 99, 'step': 7}, {'mode': 1, 'alarm': 99, 'step': 7}, {'mode': 1, 'alarm': 99, 'step': 7}]


The only way I can get it to work is If I create the dictionary directly in the append instruction (instead of using the dictionary variable).


#append the dictionary in a list
lcirc=[]
for x in range(3):
	lcirc.append({'mode':1,'alarm':4,'step':7})   #<--- NOT using dictionary variable

#modify item 'alarm' from list array 2 
lcirc[2]['alarm']=99

Result: **It works
[{'mode': 1, 'alarm': 4, 'step': 7}, {'mode': 1, 'alarm': 4, 'step': 7}, {'mode': 1, 'alarm': 99, 'step': 7}]

I am just wondering what I am doing wrong when using the dictionary variable that causes problems when trying to modify one item.. any clues?

You're adding the same dictionary instance to the list, 3 times. You're not adding copies of it.

1 Like
1 Like

wow! you are right. makes sense.. :smile:
so I will need to create a new variable during each loop or create a copy of the dictionary..
Thanks!

very useful. Actually it mention that I should be using dict.copy()
Thank you!!!

1 Like

Note, if you have nested structures, you will need to deepcopy the object to get a completely detached copy.

3 Likes

Just in time!! I was just going through that problem!...
I used deepcopy as mentioned in your link and it worked = )
Thank you!!