What is the difference between a deep copy and a shallow copy of a nested dictionary with nested mutable values in Python using recursion?Antek N
In Python, when dealing with nested dictionaries that contain mutable values (such as lists or other dictionaries), you have the option to create shallow copies or deep copies. The difference between the two lies in how they handle the references to the nested mutable values. Let's explore the concepts of deep copy and shallow copy using recursion:
1. Shallow Copy:
- A shallow copy creates a new dictionary object but maintains references to the original nested mutable values.
- If you modify one of the nested mutable values in the shallow copy, the change will be reflected in the original dictionary as well.
- Shallow copy can be performed using the dictionary'scopy()
method or thedict()
constructor.
Here's an example that demonstrates shallow copy using recursion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import copy original_dict = {'a': [1, 2], 'b': {'x': 3, 'y': 4}} shallow_copy = copy.copy(original_dict) # Or: shallow_copy = dict(original_dict) # Modifying a nested value in the shallow copy shallow_copy['a'][0] = 10 print(original_dict) # Output: {'a': [10, 2], 'b': {'x': 3, 'y': 4}} print(shallow_copy) # Output: {'a': [10, 2], 'b': {'x': 3, 'y': 4}}
In the example, modifying the value10
in the shallow copy's nested list also affects the original dictionary. This behavior occurs because both the original dictionary and the shallow copy reference the same nested mutable values.
2. Deep Copy:
- A deep copy creates a completely independent copy of the original dictionary and its nested mutable values.
- If you modify a nested mutable value in the deep copy, the original dictionary remains unchanged.
- Deep copy can be performed using thecopy
module or the dictionary'scopy.deepcopy()
method.
Here's an example that demonstrates deep copy using recursion:
1 2 3 4 5 6 7 8 9 10 11 12 13
import copy original_dict = {'a': [1, 2], 'b': {'x': 3, 'y': 4}} deep_copy = copy.deepcopy(original_dict) # Modifying a nested value in the deep copy deep_copy['a'][0] = 10 print(original_dict) # Output: {'a': [1, 2], 'b': {'x': 3, 'y': 4}} print(deep_copy) # Output: {'a': [10, 2], 'b': {'x': 3, 'y': 4}}
In this example, modifying the value10
in the deep copy's nested list does not affect the original dictionary. The deep copy creates a new dictionary object with its own independent copies of the nested mutable values.
When working with nested dictionaries that contain mutable values, it's important to consider whether you need a shallow copy or a deep copy based on your specific requirements. Shallow copy provides a more lightweight approach as it shares references, while deep copy ensures complete independence but may be less efficient for large and complex data structures.