-1

so basically i know that shallow copy and deep copy varies. what i am trying to understand is that when i make a direct copy:

d1 = {"a": "1"}
d2 = {}
d2 = d1
d1["b"] = "2"
del d1

print(d2)

this returns the output as

{"a": "1", "b": "2"}

my question is why does this happen, and what can i do to not let this happen? i dont want d2 to change once i make the copy. Is there any way to do it without using copy.deepcopy()?

Metison
  • 7
  • 4

3 Answers3

1

No you cannot copy a object like that,When you are saying d2=d1 you are not making a copy of d1, it results in d2 being just another name for d1. If you don't want it to update "b":"2" use dict(d1)

d1={"a":1}
d2=dict(d1)
d1["b"]="2"
del d1
print(d2)
Addy
  • 417
  • 4
  • 13
0

Use .copy() to create a (shallow copy) of d1 like so:

d1 = {"a": "1"}
d2 = d1.copy()
d1["a"] = "2"
print(d2)

which outputs:

{'a': '1'}

The reason the original code did not work as you expected is that both d1 and d2 were pointing at the same object.

C. Pappy
  • 739
  • 4
  • 13
0

By assigning d2 = d1 they both point to the same variable in memory. You can modify this value with either name as they both point to the same thing.

This is not a copy you are only incrementing the reference count by one. By using del d1 you are decrementing the reference count by one but d2 still points to the same value in memory.

To create a copy where they are both separate entities then use d2 = d1.copy().

Jab
  • 26,853
  • 21
  • 75
  • 114
  • so if i delete both the references d1 and d2, what happens to that memory location? does it still store the same dictionary, but without any reference to any other object there? is that what we generally term as garbage values? – Metison Jul 10 '20 at 20:21
  • There is a garbage collector that runs in the background and clears up objects with no reference count. – Jab Jul 12 '20 at 21:19