Understanding Shallow Copying
When creating a shallow copy of a dictionary, the dictionary object is not copied entirely. Instead, a new reference to the original object is created. This means that any changes made to the shallow copy will also be reflected in the original dictionary.
Example: Dictionary
Consider the following example:
original = dict(a=1, b=2) new = original.copy() new.update({'c': 3})
In this case, new is a shallow copy of original. When new is updated with {'c': 3}, the original dictionary remains unchanged because both original and new reference the same underlying object.
Contrast with Shallow Copying in Lists
Lists behave differently when shallow copied. When creating a shallow copy of a list, a new reference to the underlying list object is created. However, any changes made to the shallow copy do not affect the original list, as lists are mutable objects that can be modified independently.
Understanding Deep Copying
Unlike shallow copying, deep copying creates a new, independent copy of the original object. This means that any changes made to the deep copy will not affect the original object.
Solution
To update the original dictionary, it is necessary to create a deep copy instead of a shallow copy. The following code uses copy.deepcopy() to create a deep copy:
import copy new = copy.deepcopy(original) new.update({'c': 3})
Now, original remains untouched while new has the updated values.
The above is the detailed content of Why Doesn\'t Updating a Shallow Copy of a Dictionary Change the Original?. For more information, please follow other related articles on the PHP Chinese website!