How to copy a dictionary in Python?

Published on Aug. 22, 2023, 12:17 p.m.

In Python, you can use the copy() method or the dict() constructor to make a copy of an existing dictionary. However, there are some differences in how these strategies make copies of the dictionary. Here are some examples:

Using the copy() method:

original_dict = {1: 'one', 2: 'two', 3: 'three'}
new_dict = original_dict.copy()

# Make a change in original_dict
original_dict[1] = 'ONE'

print('original_dict:', original_dict)
print('new_dict:', new_dict)

In this example, the copy() method is used to create a new dictionary that is a shallow copy of the original_dict. This means that new dictionary contains references to the same objects as the original dictionary, rather than new copies of those objects. If any of the referenced objects are mutable, changes to those objects in the original dictionary will also be reflected in the new dictionary.

Using the dict() constructor:

original_dict = {1: 'one', 2: 'two', 3: 'three'}
new_dict = dict(original_dict)

# Make a change in original_dict
original_dict[1] = 'ONE'

print('original_dict:', original_dict)
print('new_dict:', new_dict)

In this example, the dict() constructor is used to create a new dictionary that is also a shallow copy of the original_dict. As with the copy() method, the new dictionary contains references to the same objects as the original dictionary.

If you need a deep copy of the dictionary – that is, a copy where all objects are themselves copied rather than referenced – you can use the copy module’s deepcopy() function. Here’s an example:

import copy

original_dict = {1: ['one', 'two'], 2: ['three', 'four'], 3: ['five', 'six']}
new_dict = copy.deepcopy(original_dict)

# Make a change in original_dict
original_dict[1][0] = 'ONE'

print('original_dict:', original_dict)
print('new_dict:', new_dict)

In this example, the deepcopy() function is used to create a new dictionary that is a deep copy of the original_dict. This means that all objects in the new dictionary are copied recursively, rather than just having references to the same objects as the original dictionary. Consequently, changes made to mutable objects in the original dictionary do not affect