Shallow Copy vs. Deep Copy in Python: Understanding the Effects on Dictionaries
The shallow copy of a dictionary in Python, created using dict.copy(), may not update the original dictionary as expected. This behavior stems from the concept of shallow vs. deep copying.
What is Shallow Copying?
In a shallow copy, the content of the dictionary is referenced, rather than copied by value. This means that both the original and copied dictionaries point to the same underlying data structures.
Demonstration:
>> original = dict(a=1, b=2) >> new = original.copy() >> new.update({'c': 3}) >> original {'a': 1, 'b': 2}
Contrary to the expectation, the original dictionary remains unchanged after the shallow copy is updated. This is because the references to the data are shared, not copied.
How Lists Differ:
Unlike dictionaries, shallow copying lists does result in a shared reference to the data. This is because lists contain values by reference.
>> original = [1, 2, 3] >> new = original >> new.append(4) >> new, original ([1, 2, 3, 4], [1, 2, 3, 4])
In this case, both the original and the new list reference the same data, so changes made to one affect the other.
Deep Copying with copy.deepcopy()
To create a truly distinct copy of a dictionary, including its content, copy.deepcopy() must be used. This function copies the structure and values by value, ensuring complete isolation.
import copy >> original = dict(a=1, b=2) >> new = copy.deepcopy(original) >> new.update({'c': 3}) >> original {'a': 1, 'b': 2} >> new {'a': 1, 'c': 3, 'b': 2}
Types of Copy Operations:
The above is the detailed content of Shallow vs. Deep Copy in Python Dictionaries: When Does `copy()` Fail?. For more information, please follow other related articles on the PHP Chinese website!