0

I am trying to copy a dictionary that has sets as values.

dic = {0: set([1]), 1: set([0, 2]), 2: set([1, 3]), 3: set([2, 4]), 4: set([3])}
dic1 = dic.copy()
dic1[0].update(dic[1])
print dic
print dic1

and I am getting

{0: set([0, 1, 2]), 1: set([0, 2]), 2: set([1, 3]), 3: set([2, 4]), 4: set([3])}
{0: set([0, 1, 2]), 1: set([0, 2]), 2: set([1, 3]), 3: set([2, 4]), 4: set([3])}

so basically they are now the same thing. I have tried doing dictionary comprehension and doing .copy() and nothing! How can I make it so that the original dictionary remains untouched?

I went to python tutor and basically, the keys are in dic1 but the values are linked to the ones in dic. How can I make it so they have independent values?

1 Answers1

1

You can do copy.deepcopy, like this

import copy
dic1 = copy.deepcopy(dic)

Normally when you copy a dictionary object, for each and every key-value pair, a new reference to the key is made (dictionary doesn't allow immutable objects as keys) and a new reference to the value object is also made. The new reference will also refer the same original object. Updating a set is actually mutating the object. So, the new reference and the original object will reflect the changes.

When a deepcopy is done, it actually creates a new copy of the value object (not a new reference), even though it is a mutable object. This copy is done recursively.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497