How to Copy a Dictionary in Python: Simple Methods Explained
To copy a dictionary in Python, use the
copy() method or the dict() constructor to create a shallow copy. For a deep copy that copies nested objects, use the copy.deepcopy() function from the copy module.Syntax
There are two common ways to copy a dictionary in Python:
- Using
copy()method: Creates a shallow copy of the dictionary. - Using
dict()constructor: Also creates a shallow copy by passing the original dictionary.
For deep copies (copying nested dictionaries), use copy.deepcopy() from the copy module.
python
new_dict = original_dict.copy() # or new_dict = dict(original_dict)
Example
This example shows how to copy a dictionary using copy() and how modifying the copy does not affect the original dictionary.
python
original = {'a': 1, 'b': 2}
copied = original.copy()
copied['a'] = 100
print('Original:', original)
print('Copied:', copied)Output
Original: {'a': 1, 'b': 2}
Copied: {'a': 100, 'b': 2}
Common Pitfalls
A common mistake is expecting copy() or dict() to copy nested dictionaries deeply. They only create shallow copies, so changes to nested objects affect both dictionaries.
Use copy.deepcopy() to avoid this problem.
python
import copy original = {'outer': {'inner': 1}} shallow_copy = original.copy() deep_copy = copy.deepcopy(original) shallow_copy['outer']['inner'] = 100 print('Original after shallow copy change:', original) deep_copy['outer']['inner'] = 200 print('Original after deep copy change:', original)
Output
Original after shallow copy change: {'outer': {'inner': 100}}
Original after deep copy change: {'outer': {'inner': 100}}
Quick Reference
| Method | Description |
|---|---|
copy() | Creates a shallow copy of the dictionary. |
dict() | Creates a shallow copy by passing the original dictionary. |
copy.deepcopy() | Creates a deep copy including nested objects. |
Key Takeaways
Use
copy() or dict() for a shallow copy of a dictionary.Shallow copies do not copy nested objects; changes to nested data affect both dictionaries.
Use
copy.deepcopy() to copy nested dictionaries safely.Modifying the copied dictionary does not change the original if the copy is shallow and values are immutable.
Always import the
copy module to use deepcopy().