Home > Enterprise >  Changing the initial sub-dictionary when changing a new one, when copying with copy.copy(dict[dict])
Changing the initial sub-dictionary when changing a new one, when copying with copy.copy(dict[dict])

Time:11-17

I have a dictionary of dictionaries that needs to be modified as the code progresses, but its original version will also be needed later. I know that if I just assign a new variable to a dictionary, a reference to the existing one will be created, and if I change either one of those objects, the other one will be changed as well.

I've also read here that to copy dictionaries, lists, etc you should use copy.copy, however, that doesn't work with my problem.

    from copy import copy
    a = {"1": {"1":2, "2":3}, "2":{"3":4, "4":5}}
    b = copy(a)
    b["1"].update({"4":3})
    # b == {"1": {"1":2, "2":3, "4":3}, "2":{"3":4, "4":5}}
    # a == {"1": {"1":2, "2":3, "4":3}, "2":{"3":4, "4":5}} Although "a" shouldn't change

I'm new to python, so could you please help me out?

CodePudding user response:

I made a mistake initially. The problem is that copy copies a reference to the sub object instead of the values. That's why you need deepcopy.

from copy import deepcopy
a = {"1": {"1":2, "2":3}, "2":{"3":4, "4":5}}
b = deepcopy(a)
b["1"].update({"4":3})
print(b)
print(a)
  • Related