search

How to create a deep copy of a dictionary in Python?

In Python, you can create a deep copy of a dictionary using the deepcopy() function from the copy module. A deep copy creates a completely independent copy of the dictionary, including all nested objects, by recursively copying each object. Here's how you can create a deep copy:

import copy

original_dict = {'name': 'John', 'age': 30, 'city': ['New York', 'London']}

# Create a deep copy using the deepcopy() function
deep_copy = copy.deepcopy(original_dict)

After creating a deep copy, modifications made to the keys or values in the original dictionary will not affect the deep copy, as they are now separate objects.

Let's illustrate this behavior with an example:

import copy

original_dict = {'name': 'John', 'age': 30, 'city': ['New York', 'London']}

deep_copy = copy.deepcopy(original_dict)

# Modify the original dictionary
original_dict['age'] = 31
original_dict['city'].append('Paris')

print(original_dict)  # Output: {'name': 'John', 'age': 31, 'city': ['New York', 'London', 'Paris']}
print(deep_copy)  # Output: {'name': 'John', 'age': 30, 'city': ['New York', 'London']}

In this example, modifying the 'age' key and appending a new city to the original dictionary does not affect the deep copy, as it maintains the original values.

By using copy.deepcopy(), you can create a completely independent copy of the dictionary, including nested objects. This is particularly useful when you need to work with a separate dictionary that doesn't share any references with the original one.

Related Questions You Might Be Interested