Copy Dictionaries
1. Shallow Copy using copy()
method:
# Original Dictionary
original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Shallow Copy using copy() method
copy_dict = original_dict.copy()
2. Shallow Copy using dict()
constructor:
# Original Dictionary
original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Shallow Copy using dict() constructor
copy_dict = dict(original_dict)
3. Deep Copy using copy
module:
# Original Dictionary
original_dict = {'name': 'John', 'age': 30, 'city': ['New York', 'London']}
# Deep Copy using copy module
import copy
deep_copy_dict = copy.deepcopy(original_dict)
The methods mentioned above provide different ways to create copies of dictionaries in Python. Choose the method that best suits your needs. If your dictionary contains only basic data types, a shallow copy may be sufficient. If your dictionary contains nested objects, especially mutable ones, a deep copy may be more appropriate.