How to Clone a Dictionary in Python?

Estimated read time 2 min read

To clone a dictionary in Python, you can use the copy() method from the copy module or create a new dictionary using the dict() constructor. Here are examples of both approaches:

  1. Using the copy() method:
import copy

original_dict = {'a': 1, 'b': 2, 'c': 3}

# Clone the original dictionary
cloned_dict = copy.copy(original_dict)

print(cloned_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

In this example, the copy.copy() method is used to create a shallow copy of the original dictionary original_dict. The cloned_dict variable stores the cloned dictionary, which contains the same key-value pairs as the original dictionary.

Note that the copy() method creates a shallow copy, meaning that if the dictionary contains mutable objects as values (e.g., lists or other dictionaries), the cloned dictionary will have references to the same objects as the original dictionary. To create a deep copy, including all nested objects, you can use the copy.deepcopy() method instead.

  1. Using the dict() constructor:
original_dict = {'a': 1, 'b': 2, 'c': 3}

# Clone the original dictionary
cloned_dict = dict(original_dict)

print(cloned_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

In this example, the dict() constructor is used to create a new dictionary cloned_dict with the same key-value pairs as the original dictionary original_dict. The cloned_dict variable stores the cloned dictionary.

Both approaches achieve the same result of cloning a dictionary in Python. Choose the one that is most suitable for your specific use case.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply