Table of Contents
ToggleCopying dictionaries in Python creates a new dictionary with the same key-value pairs. In this lesson, you’ll learn two main techniques—shallow copy and deep copy—and how they differ when handling nested objects. Let’s explore!
A shallow copy creates a new dictionary but references the same nested objects (like lists) as the original. Use the copy() method or dict() function.
original_dict = {"name": "Alice", "age": 25, "skills": ["Python", "Data Science"]}
shallow_copy = original_dict.copy()
shallow_copy["age"] = 26
shallow_copy["skills"].append("Machine Learning")
print("Original:", original_dict)
print("Shallow:", shallow_copy)
Output: Original: {‘name’: ‘Alice’, ‘age’: 25, ‘skills’: [‘Python’, ‘Data Science’, ‘Machine Learning’]}, Shallow: {‘name’: ‘Alice’, ‘age’: 26, ‘skills’: [‘Python’, ‘Data Science’, ‘Machine Learning’]}
Note: The list skills changes in both because it’s a reference, not a new copy.
A deep copy creates a fully independent dictionary, copying all nested objects too. Use copy.deepcopy() from the copy module.
import copy
original_dict = {"name": "Alice", "age": 25, "skills": ["Python", "Data Science"]}
deep_copy = copy.deepcopy(original_dict)
deep_copy["age"] = 26
deep_copy["skills"].append("Machine Learning")
print("Original:", original_dict)
print("Deep:", deep_copy)
Output: Original: {‘name’: ‘Alice’, ‘age’: 25, ‘skills’: [‘Python’, ‘Data Science’]}, Deep: {‘name’: ‘Alice’, ‘age’: 26, ‘skills’: [‘Python’, ‘Data Science’, ‘Machine Learning’]}
Note: The original stays unchanged because deepcopy() duplicates everything.
The copy() method is a simple way to make a shallow copy. It’s built into dictionaries—no import needed.
new_dict = original_dict.copy()
dict1 = {"name": "Krishna", "age": "27"}
dict2 = dict1.copy()
print("dict1:", dict1)
print("dict2:", dict2)
Output: dict1: {‘name’: ‘Krishna’, ‘age’: ’27’}, dict2: {‘name’: ‘Krishna’, ‘age’: ’27’}
Key Takeaway: Use copy() for shallow copies (shared nested objects) and deepcopy() for deep copies (fully independent). Choose wisely based on your needs!
