Python – Deep Copy Dictionary
In Python, a deep copy of a dictionary creates a new dictionary with entirely new key-value pairs, where the values are also deep copies of the originals.
This ensures that if the original dictionary contains mutable objects (such as lists or other dictionaries), the deep copy will have new instances of those objects rather than references to the originals.
As a result, modifying a mutable object in the deep copy does not affect the corresponding object in the original dictionary and vice-versa.
You can create a deep copy of a dictionary using the deepcopy()
function of the copy
module.
For example:
import copy
original_dict = {
'a': 1,
'b': [2, 3, 4],
'c': {'x': 5, 'y': 6}
}
# Create a deep copy of the dictionary
deep_copied_dict = copy.deepcopy(original_dict)
# Modifying the deep copied dictionary
deep_copied_dict['b'].append(10)
deep_copied_dict['c']['x'] = 20
print('Original dictionary:', original_dict)
print('Deep copied dictionary:', deep_copied_dict)
Output:
Original dictionary: {'a': 1, 'b': [2, 3, 4], 'c': {'x': 5, 'y': 6}}
Deep copied dictionary: {'a': 1, 'b': [2, 3, 4, 10], 'c': {'x': 20, 'y': 6}}
As you can see in the above example, the changes made to the deep_copied_dict
did not affect original_dict
.
Differences between dictionary deep copy vs shallow copy
Feature | Shallow copy (copy() , copy.copy() | Deep copy (copy.deepcopy() ) |
Definition | Creates a new dictionary but keeps references to nested objects. | Recursively creates a copy of all nested objects. |
Modification Impact | Changes to nested objects in the copy affect the original. | Changes to nested objects in the copy doesn’t affect the original. |
Performance | Faster (copies only top-level structure) | Slower (recursively copies all levels) |
Use Case | When nested objects don’t need to be independent. | When nested objects need to be independent. |
Code example showing the differences
import copy
original_dict = {'a': 1, 'b': {'c':2}}
# Shallow copy
shallow_copied_dict = original_dict.copy()
shallow_copied_dict['b']['c'] = 10 # Modifies the original dictionary too
print("Original dictionary:", original_dict)
print("Shallow copied dictionary:", shallow_copied_dict)
# Deep copy
deep_copied_dict = copy.deepcopy(original_dict)
deep_copied_dict['b']['c'] = 50 # Doesn't affect the original dictionary
print("Original dictionary:", original_dict)
print("Deep copied dictionary:", deep_copied_dict)
Output:
Original dictionary: {'a': 1, 'b': {'c': 10}}
Shallow copied dictionary: {'a': 1, 'b': {'c': 10}}
Original dictionary: {'a': 1, 'b': {'c': 10}}
Deep copied dictionary: {'a': 1, 'b': {'c': 50}}