mutation

dict.popitem

Removes and returns the last inserted (key, value) pair as a 2-tuple in LIFO order. Raises KeyError if the dictionary is empty.

d.popitem()

Parameters

Parameter Purpose
(no parameters) popitem takes no arguments
returns (key, value) tuple of the most recently inserted pair

Examples

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

Removes the last-inserted pair (LIFO since Python 3.7)

>>> d = {}
>>> d.popitem()
Traceback (most recent call last):
  ...
KeyError: 'popitem(): dictionary is empty'

Empty dict raises KeyError

>>> d = {'a': 1, 'b': 2}
>>> while d:
...     print(d.popitem())
('b', 2)
('a', 1)

Destructively drain a dict from newest to oldest

>>> d = {'a': 1}
>>> d['b'] = 2
>>> d.popitem()
('b', 2)

Reassigning an existing key does NOT change its insertion order

Gotcha

Since Python 3.7 popitem is LIFO, not arbitrary — code that assumed random ordering may now be deterministic. Raises KeyError (not IndexError) when the dict is empty.

Related methods

← All Python dict methods · String methods · Built-in functions