Learn How to Make a Deep Copy of a Dictionary Easily

Learn How to Make a Deep Copy of a Dictionary Easily

To create a deep copy of a dictionary in Python, you can use the copy.deepcopy() function from the copy module. This function recursively creates copies of all nested objects within the dictionary, ensuring that changes made to the original dictionary or its nested objects do not affect the copied dictionary. Here are five examples demonstrating how to create a deep copy of a dictionary:

import copy

# Example 1: Simple dictionary
original_dict1 = {'a': 1, 'b': [2, 3], 'c': {'d': 4, 'e': 5}}
deep_copied_dict1 = copy.deepcopy(original_dict1)

# Example 2: Nested dictionaries
original_dict2 = {'a': {'b': {'c': 1}}}
deep_copied_dict2 = copy.deepcopy(original_dict2)

# Example 3: Dictionary containing lists
original_dict3 = {'a': [1, 2, 3], 'b': {'c': [4, 5, 6]}}
deep_copied_dict3 = copy.deepcopy(original_dict3)

# Example 4: Dictionary with custom objects
class CustomObject:
    def __init__(self, x):
        self.x = x

original_dict4 = {'a': CustomObject(1), 'b': CustomObject(2)}
deep_copied_dict4 = copy.deepcopy(original_dict4)

# Example 5: Dictionary containing tuples
original_dict5 = {'a': (1, 2), 'b': {'c': (3, 4)}}
deep_copied_dict5 = copy.deepcopy(original_dict5)

# Printing the original and deep copied dictionaries
print("Original Dictionary 1:", original_dict1)
print("Deep Copied Dictionary 1:", deep_copied_dict1)

print("Original Dictionary 2:", original_dict2)
print("Deep Copied Dictionary 2:", deep_copied_dict2)

print("Original Dictionary 3:", original_dict3)
print("Deep Copied Dictionary 3:", deep_copied_dict3)

print("Original Dictionary 4:", original_dict4.__dict__)
print("Deep Copied Dictionary 4:", deep_copied_dict4.__dict__)

print("Original Dictionary 5:", original_dict5)
print("Deep Copied Dictionary 5:", deep_copied_dict5)

In these examples, deepcopy() ensures that modifications to the original dictionaries or their nested objects do not affect the deep copied dictionaries and vice versa.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!