How to clone a dictionary in Python – Shallow and Deep Copies

Updated: February 12, 2024 By: Guest Contributor Post a comment

Overview

One of the fundamental operations when working with data structures in Python is cloning, specifically in the context of dictionaries. Cloning can be performed at different levels, leading to shallow or deep copies. In this guide, we will explore various methods to clone dictionaries in Python, covering both basic and advanced techniques, complemented by practical examples.

What is Cloning a Dictionary?

Cloning a dictionary involves creating a duplicate that operates independently of the original. Depending on the cloning method, modifications to the clone may or may not affect the original dictionary. This is where the distinction between shallow and deep cloning becomes critical.

Shallow Cloning

In shallow cloning, only the top-level structure is duplicated, while nested structures remain shared between the clone and the original. This means that changes to nested structures in the clone will reflect in the original, and vice versa.

Example 1: Using dict.copy()

original_dict = {'key1': 'value1', 'key2': ['list', 'in', 'dict']}
clone_dict = original_dict.copy()
print("Original:", original_dict)
print("Clone:", clone_dict)

# Modifying the clone's list
glone_dict['key2'].append('modified')
print("After modification:")
print("Original:", original_dict)
print("Clone:", clone_dict)

Deep Cloning

Deep cloning, conversely, creates a completely independent copy of the dictionary, including all nested structures. Changes to the clone have no effect on the original, making it ideal for operations requiring isolation.

Example 2: Using copy.deepcopy()

import copy
original_dict = {'key1': 'value1', 'key2': {'nested_key': 'nested_value'}}
clone_dict = copy.deepcopy(original_dict)
print("Original:", original_dict)
print("Clone:", clone_dict)

# Modifying the clone's nested dictionary
clone_dict['key2']['nested_key'] = 'modified'
print("After modification:", original_dict)
print("After modification:", clone_dict)

Advanced Techniques for Dictionary Cloning

While the dict.copy() and copy.deepcopy() methods serve most needs, certain scenarios require more nuanced approaches. Let’s explore some advanced techniques for cloning dictionaries in Python.

Using Dict Comprehensions

Dict comprehensions provide a concise way to create a shallow clone of a dictionary. This method is particularly useful when you also need to transform the keys or values during the cloning process.

Example 3: Cloning with Transformation

original_dict = {'key1': 1, 'key2': 2}
clone_dict = {key: val * 2 for key, val in original_dict.items()}
print("Original:", original_dict)
print("Clone:", clone_dict)

Using Custom Functions for Deep Cloning

Sometimes, the copy.deepcopy() method might not be suitable, especially if the dictionary contains objects that require customized deep copying logic. In such cases, implementing a custom deep cloning function can be a powerful solution.

Example 4: Custom Deep Clone Function

def custom_deep_clone(dictionary):
    clone = {}
    for key, value in dictionary.items():
        if isinstance(value, dict):
            clone[key] = custom_deep_clone(value)
        else:
            clone[key] = value
    return clone

original_dict = {'key1': 'value1', 'key2': {'nested_key': 'nested_value'}}
clone_dict = custom_deep_clone(original_dict)
print("Original:", original_dict)
print("Clone:", clone_dict)

Conclusion

Cloning dictionaries in Python is a versatile operation that can be achieved through several methods, depending on the level of independence required between the original and the clone. Whether through built-in methods like dict.copy() and copy.deepcopy(), dict comprehensions, or custom functions, Python offers flexible solutions for both shallow and deep cloning. Understanding these techniques and their implications is crucial for effective data manipulation and ensuring that your programs behave as expected.