0

So a really basic example that works:

dict1 = dict({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})

dict2 = dict1.copy()

dict2['a'] = [9,9,9]

print(dict1['a'])

result: [1,2,3]

The result shows that I was able to edit the copy without changing the original.

But if I instead do:

dict1 = dict({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})

dict2 = dict1.copy()

dict2['a'][0] = 9

print(dict1['a'])

result: [9,2,3]

So it looks like using .copy() makes it so the copied dict has independent keys from the original dict, but the values associated with those keys are still connected. Is there a workaround for this? Thanks!

  • This is called shallow copy. A full explanation is in https://stackoverflow.com/questions/3975376/understanding-dict-copy-shallow-or-deep/3975388#3975388 – Ehsan May 12 '20 at 21:48

1 Answers1

2

You want to create a deep copy of the dict, otherwise the objects referenced within the dict will be shared between the original and the shallow copy (hence changing an element in your second example not working how you want):

import copy

dict1 = dict({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})

dict2 = copy.deepcopy(dict1)
Philip Ciunkiewicz
  • 2,652
  • 3
  • 12
  • 24