The copy method
The copy
method creates a copy of the dictionary. We do not specify anything in the method parameter.
Syntax
dictionary.copy()
Example
Let's copy our dictionary using the copy
method:
dct1 = {
'a': 1,
'b': 2,
'c': 3
}
dct2 = dct1.copy()
print(dct2)
Result of code execution:
{'a': 1, 'b': 2, 'c': 3}
Example
However, by using the copy
method we only create a shallow copy of the dictionary - changes we make to the original dictionary after copying will not affect the copy:
dct1 = {
'a': 1,
'b': 2,
'c': 3
}
dct2 = dct1.copy()
dct1['e'] = 4
print('dct1', dct1)
print('dct2', dct2)
Result of code execution:
dct1 {'a': 1, 'b': 2, 'c': 3, 'e': 4}
dct2 {'a': 1, 'b': 2, 'c': 3}