How to copy a dictionary and only edit the copy

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

    In addition to the other provided solutions, you can use ** to integrate the dictionary into an empty dictionary, e.g.,

    shallow_copy_of_other_dict = {**other_dict}.

    Now you will have a "shallow" copy of other_dict.

    Applied to your example:

    >>> dict1 = {"key1": "value1", "key2": "value2"}
    >>> dict2 = {**dict1}
    >>> dict2
    {'key1': 'value1', 'key2': 'value2'}
    >>> dict2["key2"] = "WHY?!"
    >>> dict1
    {'key1': 'value1', 'key2': 'value2'}
    >>>
    

    Pointer: Difference between shallow and deep copys

提交回复
热议问题