How to copy a dictionary and only edit the copy

前端 未结 20 1975
说谎
说谎 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:40

    Python never implicitly copies objects. When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.

    If you want to copy the dict (which is rare), you have to do so explicitly with

    dict2 = dict(dict1)
    

    or

    dict2 = dict1.copy()
    

提交回复
热议问题