0

The following code removes a set element from a copied dictionary, yet both dictionaries are changed. How can have dic1 remain unchanged?

dic1 = {'a': set([1,2])}
dic2 = dic1.copy()
dic2['a'].discard(1)
user1879926
  • 1,283
  • 3
  • 14
  • 24
  • Possible duplicate of [How to copy a dictionary and only edit the copy](http://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy) – Andrés Pérez-Albela H. Nov 06 '15 at 04:38

2 Answers2

2
import copy

dic1 = {'a': set([1,2])}
dic2 = copy.deepcopy(dic1)
dic2['a'].discard(1)
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
1

learn about copy — Shallow and deep copy operations to understand why copy doesn't work, but deepcopy works

Hooting
  • 1,681
  • 11
  • 20