Python Copy Dictionaries
Why Copy a Dictionary?
Copying a dictionary allows you to create a new dictionary with the same key-value pairs without affecting the original dictionary.
⚠️ Don't Copy Using Just =
(Assignment)
original = {"name": "Alice", "age": 25}
copy_dict = original
copy_dict["age"] = 30
print(original)
Output:
{'name': 'Alice', 'age': 30}
Explanation: This doesn't copy the dictionary. It only creates a reference, so changes affect both variables.
Correct Ways to Copy a Dictionary
1. Using copy()
Method
original = {"name": "Alice", "age": 25}
copy_dict = original.copy()
copy_dict["age"] = 30
print("Original:", original)
print("Copy:", copy_dict)
Output:
Original: {'name': 'Alice', 'age': 25}
Copy: {'name': 'Alice', 'age': 30}
Explanation: copy()
creates a shallow copy — a new dictionary with the same contents.
2. Using dict()
Constructor
original = {"name": "Bob", "age": 28}
copy_dict = dict(original)
copy_dict["age"] = 35
print("Original:", original)
print("Copy:", copy_dict)
Output:
Original: {'name': 'Bob', 'age': 28}
Copy: {'name': 'Bob', 'age': 35}
Explanation: dict()
is another way to create a shallow copy of the dictionary.
3. Deep Copy for Nested Dictionaries
import copy
original = {
"student": {
"name": "Eve",
"grade": "A"
}
}
deep_copy_dict = copy.deepcopy(original)
deep_copy_dict["student"]["grade"] = "B"
print("Original:", original)
print("Deep Copy:", deep_copy_dict)
Output:
Original: {'student': {'name': 'Eve', 'grade': 'A'}}
Deep Copy: {'student': {'name': 'Eve', 'grade': 'B'}}
Explanation: copy.deepcopy()
creates a full independent copy — even nested objects are cloned.
Summary of Dictionary Copy Methods
Method | Type of Copy | Use Case |
---|---|---|
copy() | Shallow | Most general use |
dict(original) | Shallow | Also creates a new dictionary |
copy.deepcopy() | Deep | Use when nested objects should be cloned |
= assignment | Reference only | ⚠️ Not a copy — both point to same object |
Conclusion
To safely copy a dictionary in Python, use .copy()
or dict()
. For nested structures, use copy.deepcopy()
to avoid unexpected changes.