Appending a dictionary to a list - I see a pointer like behavior

PythonListDictionary

Python Problem Overview


I tried the following in the python interpreter:

>>> a = []
>>> b = {1:'one'}
>>> a.append(b)
>>> a
[{1: 'one'}]
>>> b[1] = 'ONE'
>>> a
[{1: 'ONE'}]

Here, after appending the dictionary b to the list a, I'm changing the value corresponding to the key 1 in dictionary b. Somehow this change gets reflected in the list too. When I append a dictionary to a list, am I not just appending the value of dictionary? It looks as if I have appended a pointer to the dictionary to the list and hence the changes to the dictionary are getting reflected in the list too.

I do not want the change to get reflected in the list. How do I do it?

Python Solutions


Solution 1 - Python

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

Solution 2 - Python

Also with dict

a = []
b = {1:'one'}

a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]

Solution 3 - Python

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionneo29View Question on Stackoverflow
Solution 1 - PythonNPEView Answer on Stackoverflow
Solution 2 - PythoneyquemView Answer on Stackoverflow
Solution 3 - PythonMohammad EfazatiView Answer on Stackoverflow