Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

Python Concatenated list of dictionaries modifies all instances of dictionary inside the list if one of the dictionary is updated

I have a simple scenario where Python (3.7, tested also 3.5) does not seem to behave as I expect. putting it simply:

a = [{"c":1, "d":2}]
a
[{'c': 1, 'd': 2}]
b = a + a
b
[{'c': 1, 'd': 2}, {'c': 1, 'd': 2}]
b[0]
{'c': 1, 'd': 2}
b[0]['c'] = 3
b
[{'c': 3, 'd': 2}, {'c': 3, 'd': 2}]

Changing the value of an entry in the first dictionary in b, also updates the corresponding entry in the 2nd dictionary. I have tried b = a.copy() + a.copy() but got the same result. Does anyone know a way around it?

question from:https://stackoverflow.com/questions/65917803/python-concatenated-list-of-dictionaries-modifies-all-instances-of-dictionary-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use deepcopy

copy returns only a shallow copy so since your dictionary is inside the list copy will create new list but the dictionary inside the list will still reference the same dictionary.

shallow copy would work if you had this case:

a = {"c":1, "d":2}
b = [a.copy(), a.copy()] 

But in your case you need to use deepcopy

from copy import deepcopy

b = deepcopy(a) + deepcopy(a)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...