Copy Dictionaries
Shallow Copy
A shallow copy creates a new dictionary object but does not recursively copy nested mutable objects. This means changes to nested lists, sets, or dictionaries inside the copy will also affect the original.
Example
# Shallow copy methods
original = {"name": "John", "age": 30, "hobbies": ["reading", "swimming"]}
# Using copy() method
copy1 = original.copy()
# Using dict() constructor
copy2 = dict(original)
# Using dictionary comprehension
copy3 = {k: v for k, v in original.items()}
# Modify the copy
copy1["age"] = 31
copy1["hobbies"].append("cycling")
print("Original:", original)
print("Copy 1:", copy1)
print("Copy 2:", copy2)
print("Copy 3:", copy3)
Output
Original: {'name': 'John', 'age': 30, 'hobbies': ['reading', 'swimming', 'cycling']} Copy 1: {'name': 'John', 'age': 31, 'hobbies': ['reading', 'swimming', 'cycling']} Copy 2: {'name': 'John', 'age': 30, 'hobbies': ['reading', 'swimming', 'cycling']} Copy 3: {'name': 'John', 'age': 30, 'hobbies': ['reading', 'swimming', 'cycling']}
Deep Copy
A deep copy creates a new dictionary and recursively copies all nested objects. This ensures that modifying nested values in the copy does not affect the original dictionary.
Example
# Deep copy
import copy
original = {"name": "John", "age": 30, "hobbies": ["reading", "swimming"]}
# Create deep copy
deep_copy = copy.deepcopy(original)
# Modify the copy
deep_copy["age"] = 31
deep_copy["hobbies"].append("cycling")
print("Original:", original)
print("Deep copy:", deep_copy)
Output
Original: {'name': 'John', 'age': 30, 'hobbies': ['reading', 'swimming']} Deep copy: {'name': 'John', 'age': 31, 'hobbies': ['reading', 'swimming', 'cycling']}
When to Use Shallow vs Deep Copy
- Use shallow copy when:
- - The dictionary contains only immutable values (numbers, strings, tuples).
- - You want a new dictionary but do not need independent copies of nested objects.
- - Performance is important (shallow copies are faster).
- Use deep copy when:
- - The dictionary contains mutable values (lists, sets, or other dictionaries).
- - You need completely independent copies of all nested objects.
- - You want to modify nested objects in the copy without affecting the original.