user1879926
user1879926

Reputation: 1323

How to remove set element in copied object

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

Answers (2)

Hooting
Hooting

Reputation: 1711

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

Upvotes: 1

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

import copy

dic1 = {'a': set([1,2])}
dic2 = copy.deepcopy(dic1)
dic2['a'].discard(1)

Upvotes: 3

Related Questions