The copy method

The copy method creates a copy of the dictionary. We do not specify anything in the method parameter.

Syntax

pythondictionary.copy()

Example

Let's copy our dictionary using the copy method:

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

dct2 = dct1.copy()
print(dct2)

Result of code execution:

python{'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:

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

dct2 = dct1.copy()
dct1['e'] = 4

print('dct1', dct1)
print('dct2', dct2)

Result of code execution:

pythondct1 {'a': 1, 'b': 2, 'c': 3, 'e': 4}
dct2 {'a': 1, 'b': 2, 'c': 3}

See also

  • method clear,
    which deletes all elements of the dictionary
  • method update,
    which updates a dictionary with the keys and values ​​of another dictionary
  • function len,
    which returns the length of the dictionary