How to Copy a Nested Dictionary in Python?

Estimated read time 1 min read

To copy a nested dictionary in Python, you can use the copy module’s deepcopy() function. Here’s an example:

import copy

original_dict = {
    'key1': {
        'nested_key1': 'value1',
        'nested_key2': 'value2'
    'key2': {
        'nested_key3': 'value3',
        'nested_key4': 'value4'

copied_dict = copy.deepcopy(original_dict)

In this example, we create a nested dictionary called original_dict with two keys, each containing another dictionary as its value. We then use the deepcopy() function from the copy module to create a new dictionary called copied_dict that is a deep copy of the original dictionary.

A deep copy creates a new object with a new memory address, and recursively copies all objects within the original object, including any nested objects, such as other dictionaries, lists, or tuples. This ensures that any changes made to the copied object do not affect the original object, or any of its nested objects.

Note that if your nested dictionary contains objects that cannot be deep-copied, such as file objects or sockets, then deepcopy() will raise a TypeError. In such cases, you can consider using other copying methods, such as creating a new dictionary by iterating over the original dictionary and copying each key-value pair individually.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply