23 of 151 menu

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

list.popitem()

Example

Let's apply the popitem method to our dictionary:

dct = { 'a': 1, 'b': 2, 'c': 3 } print(dct.popitem()) print(dct)

Result of code execution:

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

Example

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

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

Result of code execution:

KeyError: '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
byenru