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
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)