Open In App

Python Create Deepcopy Of Dictionary Without Using Copy Module

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

When we work with dictionaries in Python, it is important to create independent copies that do not share references to the original data. This concept is known as deep copying which ensures that modifications made to one copy don’t inadvertently affect the other. In this article, we will explore different approaches to creating a deepcopy of a dictionary without importing a copy in Python.

Python Deepcopy Of Dictionary Without Using Copy Module

Below are the possible approaches to creating a Deepcopy of a Dictionary In Python

  • Using a Dictionary Comprehension
  • Using Recursion
  • Using JSON Serialization and Deserialization
  • Using the eval Function

Deepcopy Of Dictionary Using a Dictionary Comprehension

The below approach code uses dictionary comprehensions to create a new dictionary with recursively copied elements. For dictionaries, each key-value pair is mapped to a new key-value pair where the value is a deep copy using the same function. This method is efficient and readable for simpler data structures.

Python3




# Original dictionary
original_dict = {'title': 'GeeksforGeeks',
                 'website': {'category': 'Computer Science'}}
 
# Using dictionary comprehension for deep copy
copied_dict = {key: value if not isinstance(value, dict) else {
    k: v for k, v in value.items()} for key, value in original_dict.items()}
 
# Modify the copied_dict to demonstrate deep copying
copied_dict['website']['category'] = 'Programming'
 
# Output
print("Original Dictionary:")
print(original_dict)
print("Copied Dictionary:")
print(copied_dict)


Output

Original Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Computer Science'}}
Copied Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}

Deepcopy Of Dictionary Using Recursion

The below approach code uses a recursive function that calls itself to handle nested structures. For dictionaries, it creates a new dictionary and iterates through the original, deep-copying each key-value pair using the same function for nested elements. This method offers flexibility for complex data structures but can be slightly less efficient than comprehensions for simpler cases.

Python3




def deepcopy_dict(d):
    new_dict = {}
    for key, value in d.items():
        if isinstance(value, dict):
            new_dict[key] = deepcopy_dict(value)
        else:
            new_dict[key] = value
    return new_dict
 
# Original dictionary
original_dict = {'title': 'GeeksforGeeks',
                 'website': {'category': 'Computer Science'}}
 
# Deep copy using recursion
copied_dict = deepcopy_dict(original_dict)
 
# Modify the copied_dict to demonstrate deep copying
copied_dict['website']['category'] = 'Programming'
 
# Output
print("Original Dictionary:")
print(original_dict)
print("Copied Dictionary:")
print(copied_dict)


Output

Original Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Computer Science'}}
Copied Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}

Deepcopy Of Dictionary Using JSON Serialization and Deserialization

The below approach code uses JSON Serialization and Deserialization, effectively serializing its data. It then deserializes the JSON string back into a new dictionary, creating a deep copy. This method is straightforward and works for various data types but might incur overhead compared to other methods.

Python3




import json
 
# Original dictionary
original_dict = {'title': 'GeeksforGeeks',
                 'website': {'category': 'Computer Science'}}
 
# Using JSON serialization and deserialization
copied_dict = json.loads(json.dumps(original_dict))
 
# Modify the copied_dict to demonstrate deep copying
copied_dict['website']['category'] = 'Programming'
 
# Output
print("Original Dictionary:")
print(original_dict)
print("Copied Dictionary:")
print(copied_dict)


Output

Original Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Computer Science'}}
Copied Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}

Deepcopy Of Dictionary Using the eval() Function

This approach uses the eval function to execute the JSON string as Python code, effectively creating a new object from the deserialized data.

Python3




# Original dictionary
original_dict = {'title': 'GeeksforGeeks', 'website': {'category': 'Computer Science'}}
 
# Using the eval function
copied_dict = eval(repr(original_dict))
 
# Modify the copied_dict to demonstrate deep copying
copied_dict['website']['category'] = 'Programming'
 
# Output
print("Original Dictionary:")
print(original_dict)
print("Copied Dictionary:")
print(copied_dict)


Output

Original Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Computer Science'}}
Copied Dictionary:
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads