To copy dictionary in Python, we have multiple ways available based on requirement.
Using copy() Method
The easiest way to copy a dictionary in Python is by using copy() method. This method creates a shallow copy of the dictionary. It means that the new dictionary will have the same keys and values as the original dictionary but if any of the values are mutable (like lists or other dictionaries), they will not be copied but referenced.
Python
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = d1.copy()
print(d1)
print(d2)
Output{'a': 1, 'b': 2, 'c': 3}
{'a': 1, 'b': 2, 'c': 3}
The copy() method works well for simple cases where you don't need to worry about nested mutable objects.
Let's explore other methods of copying a python dictionary:
Using copy Module for Deep Copy
The copy module provides a method called deepcopy() that is used to create a deep copy of a dictionary. A deep copy ensures that nested dictionaries or mutable objects within the dictionary are also copied, not just referenced. This is important when we want to avoid changes to nested objects in the copied dictionary affecting the original one.
Python
import copy
d1 = {'a': 1, 'b': {'x': 10, 'y': 20}, 'c': 3}
d2 = copy.deepcopy(d1)
# Modify a nested dictionary
d2['b']['x'] = 99
print(d1)
print(d2)
Output{'a': 1, 'b': {'x': 10, 'y': 20}, 'c': 3}
{'a': 1, 'b': {'x': 99, 'y': 20}, 'c': 3}
Notice that the d1 remains unchanged, while the d2 reflects the modifications. This is the power of deepcopy()—it handles nested dictionaries and other mutable objects.
Using Dictionary Comprehension
If we want more control over the copying process or need to transform the dictionary while copying it, we can use dictionary comprehension. This method allows you to create a new dictionary by iterating over the original one and applying custom logic to each key-value pair.
Python
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {key: value for key, value in d1.items()}
print(d1)
print(d2)
Output{'a': 1, 'b': 2, 'c': 3}
{'a': 1, 'b': 2, 'c': 3}
This is another way to copy a dictionary but it also allows for additional transformations to the data if needed such as modifying values or filtering items.
Using dict() Constructor
We can also create a copy of a dictionary by passing the original dictionary to the dict() constructor. This also creates a shallow copy of the dictionary, similar to the copy() method.
Python
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = dict(d1)
print(d1)
print(d2)
Output{'a': 1, 'b': 2, 'c': 3}
{'a': 1, 'b': 2, 'c': 3}
This method is another simple and effective way to copy dictionaries.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice