How to copy a dictionary and only edit the copy

前端 未结 20 2020
说谎
说谎 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条回答
  •  -上瘾入骨i
    2020-11-21 07:37

    When you assign dict2 = dict1, you are not making a copy of dict1, it results in dict2 being just another name for dict1.

    To copy the mutable types like dictionaries, use copy / deepcopy of the copy module.

    import copy
    
    dict2 = copy.deepcopy(dict1)
    

提交回复
热议问题