-3

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}}
user3141181
  • 99
  • 1
  • 11
  • 1
    Does this answer your question? [What is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment-oper). Also [What is the difference between a deep copy and a shallow copy?](https://stackoverflow.com/q/184710/4046632). – buran Jun 20 '22 at 05:57

2 Answers2

2

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).

flakes
  • 21,558
  • 8
  • 41
  • 88
0
 graph = ugraph.copy() 

does a shallow copy of the object. What you need to perform is a deep copy which can be done using:

import copy
graph = copy.deepcopy(ugraph)

While copy.copy() will do a shallow copy, copy.deepcopy() performs a deepcopy.

The main difference between deepcopy and shallow copy is as follows:

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively,
    inserts copies into it of the objects found in the original.

You can go through this question here for more explanation.

Akhil Sharma
  • 133
  • 1
  • 10