The popitem method

The popitem method removes a key-value pair from the end of a dictionary, returning a tuple of the removed pair. We do not specify anything in the method parameter.

Syntax

pythonlist.popitem()

Example

Let's apply the popitem method to our dictionary:

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

print(dct.popitem())
print(dct)

Result of code execution:

python('c', 3)
{'a': 1, 'b': 2}

Example

Now let's try applying the popitem method to an empty dictionary:

pythondct = {}
print(dct.popitem())
print(dct)

Result of code execution:

errorKeyError: 'popitem(): dictionary is empty'

See also

  • method items,
    which returns a key-value tuple of the specified dictionary
  • method get,
    which returns a dictionary value by key
  • method update,
    which updates a dictionary with the keys and values ​​of another dictionary