When using del
or .pop()
on x_copy
, the operation is magically applied to x
as well. i.e. keys in both dictionaries are deleted.
Example code:
x = {
"key1": 0,
"key2": 0,
}
x_copy = x
x_copy.pop("key1")
print(f"x = {x}")
print(f"x copy = {x_copy}")
This code should only remove the key from x
, but the key is lost from both dictionaries.
Actual output:
>>> x = {'key2': 0}
>>> x copy = {'key2': 0}
Expected output
>>> x = {'key1': 0, 'key2': 0}
>>> x copy = {'key2': 0}
Same happens if I replace .pop()
with del
:
x_copy = x
x_copy.pop("key1")
Why is this happening?
Python 3.10