What is the difference between a shallow copy and a deep copy of a nested dictionary with nested mutable values in Python using the copy module?Rashid D
In Python, thecopy
module provides two main methods for creating copies of objects: shallow copy and deep copy. Let's explore the differences between shallow copy and deep copy when working with nested dictionaries that contain nested mutable values:
Shallow Copy:
- 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 thecopy()
method from thecopy
module or the dictionary'scopy()
method.
Here's an example to demonstrate shallow copy using thecopy
module:
1 2 3 4 5 6 7 8 9 10 11 12
import copy original_dict = {'key': [1, 2, 3]} shallow_copy = copy.copy(original_dict) # Modifying a nested list in the shallow copy shallow_copy['key'][0] = 10 print(original_dict) # Output: {'key': [10, 2, 3]} print(shallow_copy) # Output: {'key': [10, 2, 3]}
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.
Deep Copy:
- 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 thedeepcopy()
method from thecopy
module.
Here's an example to demonstrate deep copy using thecopy
module:
1 2 3 4 5 6 7 8 9 10 11 12
import copy original_dict = {'key': [1, 2, 3]} deep_copy = copy.deepcopy(original_dict) # Modifying a nested list in the deep copy deep_copy['key'][0] = 10 print(original_dict) # Output: {'key': [1, 2, 3]} print(deep_copy)# Output: {'key': [10, 2, 3]}
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.
To summarize, a shallow copy of a nested dictionary maintains references to the original nested mutable values, while a deep copy creates a new dictionary object and recursively copies all nested mutable values, creating separate and independent copies.
Understanding the distinction between shallow copy and deep copy is important when working with nested dictionaries containing nested mutable values. Thecopy
module provides the necessary methods to perform shallow and deep copying in Python.