How to copy a dictionary and only edit the copy

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

    On python 3.5+ there is an easier way to achieve a shallow copy by using the ** unpackaging operator. Defined by Pep 448.

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

    ** unpackages the dictionary into a new dictionary that is then assigned to dict2.

    We can also confirm that each dictionary has a distinct id.

    >>>id(dict1)
     178192816
    
    >>>id(dict2)
     178192600
    

    If a deep copy is needed then copy.deepcopy() is still the way to go.

提交回复
热议问题