How to copy a dictionary and only edit the copy

前端 未结 20 2396
说谎
说谎 2020-11-21 06:59

Can someone please explain this to me? This doesn\'t make any sense to me.

I copy a dictionary into another and edit the second and both are changed. Why is this hap

20条回答
  •  孤城傲影
    2020-11-21 07:43

    Every variable in python (stuff like dict1 or str or __builtins__ is a pointer to some hidden platonic "object" inside the machine.

    If you set dict1 = dict2,you just point dict1 to the same object (or memory location, or whatever analogy you like) as dict2. Now, the object referenced by dict1 is the same object referenced by dict2.

    You can check: dict1 is dict2 should be True. Also, id(dict1) should be the same as id(dict2).

    You want dict1 = copy(dict2), or dict1 = deepcopy(dict2).

    The difference between copy and deepcopy? deepcopy will make sure that the elements of dict2 (did you point it at a list?) are also copies.

    I don't use deepcopy much - it's usually poor practice to write code that needs it (in my opinion).

提交回复
热议问题