Open In App

Create Deepcopy Of Dictionary Without Using Copy Module - Python

Last Updated : 01 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of creating a deep copy of a dictionary in Python without using the copy module involves duplicating a dictionary such that changes made to the copied version do not affect the original dictionary.

For example, given the dictionary a = {'title': 'GeeksforGeeks', 'website': {'category': 'Computer Science'}}, a deep copy creates a new dictionary with the same structure but independent contents. After deep copying, modifying b['website']['category'] = 'Programming' will not affect the original dictionary a, while b reflects the change.

Using dictionary comprehension

Dictionary comprehension is a efficient way to create a new dictionary while iterating over an existing one. This method works well for shallowly nested dictionaries, where only the first level contains nested structures. The key idea is to iterate over each key-value pair and check if the value is another dictionary. If it is, we create a new dictionary for that nested structure using another comprehension otherwise we copy the value directly.

Python
a = {'title': 'GeeksforGeeks',
    'website': {'cat': 'Computer Science'}}

b = {key: val if not isinstance(val, dict) else {
    k: v for k, v in val.items()} for key, val in a.items()}

b['website']['cat'] = 'Programming'
print(b)

Output
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}

Explanation:

  • List comprehension creates a shallow copy of a, copying non-dictionary values and creating new dictionaries for nested ones at the first level.
  • Modifying b['website']['cat'] = 'Programming' affects only b, not a.

Using json serialization

JSON serialization is an effective way to create a deep copy of a dictionary, especially when dealing with deeply nested structures. This method works by first converting the dictionary into a JSON string using json.dumps() and then converting it back into a new dictionary using json.loads(). Since JSON serialization reconstructs a completely new object, the resulting dictionary is fully independent of the original, ensuring that changes in the copy do not affect the original dictionary.

Python
import json

a = {'title': 'GeeksforGeeks',
     'website': {'cat': 'Computer Science'}}

b = json.loads(json.dumps(a))
b['website']['cat'] = 'Programming'

print(b)

Output
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}

Explanation:

  • json.dumps(a) converts the dictionary a into a JSON string and json.loads(json.dumps(a)) deserializes it back into a new dictionary b, creating a deep copy.
  • Modifying b['website']['category'] = 'Programming' affects only b, leaving a unchanged.

Using recursive function

Recursive function provides a flexible way to perform deep copying for dictionaries of any depth. In this approach, we define a function that iterates through each key-value pair in the dictionary. If a value is a dictionary itself, the function calls itself recursively to ensure all levels of nesting are deeply copied. Otherwise, the value is copied directly.

Python
def fun(d):
    return {k: fun(v) if isinstance(v, dict) else v for k, v in d.items()}

a = {'title': 'GeeksforGeeks',
     'website': {'cat': 'Computer Science'}}

b = fun(a)  # Recursively deep copies 'a'
b['website']['cat'] = 'Programming'

print(b)

Output
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}

Explanation:

  • fun(d) function recursively deep copies a dictionary, handling nested dictionaries and directly returning non-dictionary values.
  • Calling fun(a) creates an independent copy of a and modifying b['website']['category'] = 'Programming' affects only b, not a.

Using eval()

eval() can be used to create a deep copy of a dictionary by first converting the dictionary into its string representation using repr(), then evaluating the string back into a dictionary. This method effectively reconstructs a new dictionary object, ensuring that it is independent of the original.

Python
a = {'title': 'GeeksforGeeks',
     'website': {'cat': 'Computer Science'}}

b = eval(repr(a))
b['website']['cat'] = 'Programming'

print(b)

Output
{'title': 'GeeksforGeeks', 'website': {'category': 'Programming'}}

Explanation:

  • repr(a) generates a string representation of the dictionary a.
  • eval(repr(a)) evaluates this string to return a new dictionary, effectively creating a deep copy of a.
  • Modifying b['website']['cat'] = 'Programming' changes b without affecting a.

Next Article
Practice Tags :

Similar Reads