In this tutorial, we will look at how to copy a dictionary in Python. A dictionary is a built-in data type in Python.
It stores key-value pairs. You may find yourself needing to create a copy of a dictionary for many reasons, such as modifying the copy without affecting the original dictionary. This can be accomplished in a few different ways in Python.
1. Using the Copy() Method
Python’s dictionary object has a built-in method called copy(). This method returns a copy of the dictionary.
1 2 3 4 5 6 |
# Example of using copy() method original_dict = {"name": "John", "age": 30, "city": "New York"} copy_dict = original_dict.copy() print("Original", original_dict) print("Copy", copy_dict) |
2. Using the Dict() Constructor
Another way to copy a dictionary in Python is by using the dict() constructor. It creates a new dictionary which is a copy of the original dictionary.
1 2 3 4 5 6 |
# Example of using dict() constructor original_dict = {"name": "John", "age": 30, "city": "New York"} copy_dict = dict(original_dict) print("Original", original_dict) print("Copy", copy_dict) |
3. Using the Copy Module
Python also offers a module for creating copies known as the copy module. The copy() function of this module can also be used to create a copy of the dictionary.
The difference between the copy method and the copy module is that the copy method creates a shallow copy of the dictionary, while the copy module provides both shallow and deep copy capabilities.
1 2 3 4 5 6 7 8 9 10 |
# Example of using copy module import copy original_dict = {"name": "John", "age": 30, "city": "New York"} shallow_copy_dict = copy.copy(original_dict) deep_copy_dict = copy.deepcopy(original_dict) print("Original", original_dict) print("Shallow Copy", shallow_copy_dict) print("Deep Copy", deep_copy_dict) |
Full Code
Following is the full code utilizing the three methods for copying a dictionary:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Copying with copy() method original_dict = {"name": "John", "age": 30, "city": "New York"} copy_dict = original_dict.copy() print("Original", original_dict) print("Copy", copy_dict) # Copying with dict() constructor copy_dict = dict(original_dict) print("Copy", copy_dict) # Copying with copy module import copy shallow_copy_dict = copy.copy(original_dict) deep_copy_dict = copy.deepcopy(original_dict) print("Shallow Copy", shallow_copy_dict) print("Deep Copy", deep_copy_dict) |
Conclusion
Creating a copy of the dictionary in Python can be accomplished in several ways, including the dict.copy() method, using the dict() constructor, or using the copy.copy() and copy.deepcopy() functions in Python’s copy module.
Remember, understanding the differences between deep and shallow copies is crucial when working with mutable objects such as dictionaries. For a deeper look at this, please refer to the official Python documentation on the copy module.