How to copy a dictionary and only edit the copy

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

    dict1 is a symbol that references an underlying dictionary object. Assigning dict1 to dict2 merely assigns the same reference. Changing a key's value via the dict2 symbol changes the underlying object, which also affects dict1. This is confusing.

    It is far easier to reason about immutable values than references, so make copies whenever possible:

    person = {'name': 'Mary', 'age': 25}
    one_year_later = {**person, 'age': 26}  # does not mutate person dict
    

    This is syntactically the same as:

    one_year_later = dict(person, age=26)
    

提交回复
热议问题