Reputation: 1323
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)
Upvotes: 1
Views: 440
Reputation: 1711
learn about copy — Shallow and deep copy operations to understand why copy
doesn't work, but deepcopy
works
Upvotes: 1
Reputation: 11420
import copy
dic1 = {'a': set([1,2])}
dic2 = copy.deepcopy(dic1)
dic2['a'].discard(1)
Upvotes: 3