Copying a dictionary in a dictionary (nested dictionary)

I have a dictionary like dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}}(which also has a dictionary as meaning). I want to keep these values ​​the same for some verification purposes. So now I am copying this dictionary to another dictionary like dict2 = dict1.copy(). Now I am changing the values dict2as to { 0 : -1, 1 : -2, 2: { 0 : -1, i : -2}}. Now the problem is that the meaning of the dictionary dict1also changes as { 0 : 0, 1 : 1, 2:{ 0 : -1, 1 : -2}}. Here you can easily see this value dict1, value 2, also changing as the values ​​of the dict2 key.

How can I copy dict2from dict1, so if I change the value of key dict22, this should not affect the values ​​of dict1key = 2?

+3
source share
1 answer

Use copy.deepcopyto make a deep copy.

+11
source

Source: https://habr.com/ru/post/1734686/


All Articles