Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coping dictionary within a dictionary(Nested dictionary)

I am having a dictionary like as dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}} (which is also having a dictionary as value). I want to keep store these value same for some modification checking purpose. So now I am copy this dictionary content into another dictionary as dict2 = dict1.copy(). Now I am changing the values of dict2 like as { 0 : -1, 1 : -2, 2: { 0 : -1, i : -2}}. Now the problem is that my dict1's dictionary value also changing as { 0 : 0, 1 : 1, 2:{ 0 : -1, 1 : -2}}. Here you can see this easily dict1's key 2 values also changing as dict2's key 2 values.

How should I copy the dict2 from dict1 so if change dict2's key 2 value this should not put a impact on the dict1's key = 2 values?

like image 381
mukul sharma Avatar asked Sep 28 '26 22:09

mukul sharma


1 Answers

Use copy.deepcopy to perform a deep copy.

like image 128
kennytm Avatar answered Sep 30 '26 12:09

kennytm