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
dict.pop
Removes the specified key and returns its value. If the key is missing, returns default if provided; otherwise raises KeyError.
dict.clear
Removes all items from the dictionary in place, leaving it empty. Returns None.
dict.items
Returns a dynamic view of (key, value) tuple pairs. The view is set-like when all values are hashable and reflects subsequent changes to the dictionary.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
dict[key] = value
Assigns value to key using bracket subscription syntax, invoking __setitem__ under the hood. Creates the entry if key is absent, or overwrites the existing value; preserves the original insertion order when the key already exists.
← All Python dict methods · String methods · Built-in functions