The copy Method in Python: Copying a Dictionary

Returns a copy of a dictionary.

copy()

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict_copy = my_dict.copy()  # {'a': 1, 'b': 2, 'c': 3}

The copy is shallow, meaning it doesn’t recursively copy nested elements. Changes in nested lists will appear in the original dictionary:

second_dict = {'a': [1, 2], 'b': [3, 4]}
second_dict_copy = second_dict.copy()  # {'a': [1, 2], 'b': [3, 4]}
second_dict['a'].append(5)  # second_dict = {'a': [1, 2, 5], 'b': [3, 4]}
print(second_dict_copy)  # {'a': [1, 2, 5], 'b': [3, 4]}

For deep copying, use the copy module:

import copy

deep_dict = {'a': [1, 2], 'b': [3, 4]}
deep_dict_copy = copy.deepcopy(deep_dict)
deep_dict['a'].append(5)  # deep_dict = {'a': [1, 2, 5], 'b': [3, 4]}
print(deep_dict_copy)  # {'a': [1, 2], 'b': [3, 4]}