In Python, you can copy a dictionary using either a shallow copy or a deep copy.
A shallow copy creates a new dictionary object that contains references to the same objects as the original dictionary, while a deep copy creates a new dictionary object that contains copies of the objects in the original dictionary.
Here are the two methods for copying a dictionary in Python:
- Shallow copy:
You can create a shallow copy of a dictionary using the copy() method.
Here's an example:
original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
shallow_copy_dict = original_dict.copy()
# Modify the shallow copy
shallow_copy_dict['city'] = 'San Francisco'
# Print both dictionaries
print(original_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
print(shallow_copy_dict) # Output: {'name': 'John', 'age': 30, 'city': 'San Francisco'}
As you can see from the example, the shallow_copy_dict dictionary contains a reference to the same objects as the original_dict dictionary. When we modify the 'city' key in the copied dictionary, the same change is not reflected in the original dictionary.
- Deep copy:
You can create a deep copy of a dictionary using the copy module's deepcopy() method.
Here's an example:
import copy
original_dict = {'name': 'John', 'age': 30, 'city': ['New York', 'Los Angeles']}
deep_copy_dict = copy.deepcopy(original_dict)
# Modify the deep copy
deep_copy_dict['city'].append('San Francisco')
# Print both dictionaries
print(original_dict) # Output: {'name': 'John', 'age': 30, 'city': ['New York', 'Los Angeles']}
print(deep_copy_dict) # Output: {'name': 'John', 'age': 30, 'city': ['New York', 'Los Angeles', 'San Francisco']}
As you can see from the example, the deep_copy_dict dictionary contains a copy of the objects in the original_dict dictionary. When we modify the list object in the copied dictionary, the change is not reflected in the original dictionary.
In general, a shallow copy is sufficient for most use cases. However, if the dictionary contains nested objects or objects that are mutable, a deep copy may be necessary to avoid unexpected behavior.