How to Deep Copy a Dictionary in Python: Syntax and Examples
To deep copy a dictionary in Python, use the
deepcopy() function from the copy module. This creates a new dictionary with all nested objects copied, so changes to the copy do not affect the original.Syntax
Use the deepcopy() function from the copy module to create a deep copy of a dictionary. This copies the dictionary and all nested objects inside it.
import copy: imports the copy modulecopy.deepcopy(original_dict): returns a deep copy oforiginal_dict
python
import copy
new_dict = copy.deepcopy(original_dict)Example
This example shows how modifying a nested list inside a deep copied dictionary does not affect the original dictionary.
python
import copy original = {'numbers': [1, 2, 3], 'letters': ['a', 'b', 'c']} copy_dict = copy.deepcopy(original) copy_dict['numbers'].append(4) print('Original:', original) print('Copy:', copy_dict)
Output
Original: {'numbers': [1, 2, 3], 'letters': ['a', 'b', 'c']}
Copy: {'numbers': [1, 2, 3, 4], 'letters': ['a', 'b', 'c']}
Common Pitfalls
A common mistake is using dict.copy() or copy.copy() which only create shallow copies. Shallow copies duplicate the top-level dictionary but keep references to nested objects, so changes inside nested objects affect both dictionaries.
Always use copy.deepcopy() when you want a fully independent copy including nested objects.
python
import copy original = {'data': [1, 2, 3]} shallow_copy = original.copy() # or copy.copy(original) shallow_copy['data'].append(4) print('Original after shallow copy change:', original) # Correct way deep_copy = copy.deepcopy(original) deep_copy['data'].append(5) print('Original after deep copy change:', original)
Output
Original after shallow copy change: {'data': [1, 2, 3, 4]}
Original after deep copy change: {'data': [1, 2, 3, 4]}
Quick Reference
- Shallow copy:
dict.copy()orcopy.copy()- copies only top-level dictionary - Deep copy:
copy.deepcopy()- copies dictionary and all nested objects - Use deep copy to avoid shared references in nested data
Key Takeaways
Use copy.deepcopy() to create a fully independent copy of a dictionary including nested objects.
Shallow copies only duplicate the top-level dictionary and keep references to nested objects.
Modifying nested objects in a shallow copy affects the original dictionary.
Always import the copy module before using deepcopy.
Deep copying is essential when working with complex nested data structures.