Home > Back-end >  Python unintentionally deleting keys in other dictionaries
Python unintentionally deleting keys in other dictionaries

Time:02-10

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

CodePudding user response:

x_copy = x gives you 2 variables pointing at the same place in memory and all the operations that modify one will be reflected in another. You need to actually create another object in memory (e.g. with x.copy())and then you can treat it as an indepentant copy. https://moonbooks.org/Articles/How-to-copy-a-dictionary-in-python-/

CodePudding user response:

Didn't make shallow copy

x.copy()

Answered by @matszwecja

  • Related