Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – removing element from dicts copy affects the original dict

I am copying a dict and removing element from it. But this is affecting the original dict:

ugraph = {0: {1}, 1: {0, 2}, 2: {1, 3}, 3: {2}}
print(ugraph)
graph = ugraph.copy()
graph[0].remove(1)
print(ugraph)

gives the output:

{0: {1}, 1: {0, 2}, 2: {1, 3}, 3: {2}}
{0: set(), 1: {0, 2}, 2: {1, 3}, 3: {2}}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Hello you need to use deepcopy in that case.

from copy import deepcopy
...
graph = deepcopy(ugraph)

copy doesn’t work here because you have a dict of mutable object(in your case dictionaries).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading