To clone a dictionary in Python, you can use the copy()
method for a shallow copy or the deepcopy()
method from the copy
module for a deep copy. This allows you to create a duplicate of the original dictionary.
copy()
MethodWe can clone a dictionary in Python using the copy()
method. This example demonstrates how to declare and initialize a dictionary, use the copy()
method to clone it, and print the cloned dictionary.
For example,
original_dict
with integer keys and string values.copy()
method to create a shallow copy of the original dictionary.original_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Clone the dictionary using the copy() method
cloned_dict = original_dict.copy()
# Print the cloned dictionary
print('Cloned dictionary:')
for key, value in cloned_dict.items():
print(f'Key: {key}, Value: {value}')
Cloned dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
deepcopy()
MethodWe can clone a dictionary in Python using the deepcopy()
method from the copy
module. This example demonstrates how to declare and initialize a dictionary, use the deepcopy()
method to clone it, and print the cloned dictionary.
For example,
copy
module.original_dict
with integer keys and string values.deepcopy()
method to create a deep copy of the original dictionary.import copy
original_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Clone the dictionary using the deepcopy() method
cloned_dict = copy.deepcopy(original_dict)
# Print the cloned dictionary
print('Cloned dictionary:')
for key, value in cloned_dict.items():
print(f'Key: {key}, Value: {value}')
Cloned dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
In this tutorial, we learned How to Clone a Dictionary in Python language with well detailed examples.