popitem() removes the pair that was inserted last and returns it as a (key, value) tuple. Since Python 3.7 this LIFO (last in, first out) order is guaranteed.
That makes a dict usable as a stack of named entries, for example an undo history. It takes no arguments, and calling it on an empty dict raises KeyError.
dict.popitem() is an instance method of the built-in dict type: call it on a dictionary with dot notation, such as edits.popitem(...). No import is needed.
Syntax
Call it with no arguments and unpack the returned pair if you like.
python
key, value = d.popitem()
pair = d.popitem()
Call
What it does
{"a": 1, "b": 2}.popitem()
Returns ('b', 2), the last inserted pair.
{"only": 0}.popitem()
Returns ('only', 0); the dict becomes {}.
{}.popitem()
Raises KeyError.
To take a specific key out instead, use pop(); to empty the whole dict at once, use clear().
Method signatures
python
dict.popitem()
# returns: the last inserted (key, value) pair, as a tuple
Parameters
popitem() takes no parameters; you cannot choose which pair it removes.
Return Value
Return Value
Description
tuple
A 2-tuple (key, value) for the most recently inserted key. That pair is no longer in the dict.
Python Examples
Example 1 — Undo the Latest Edits in a Text Editor
Record edits as named steps, then undo them newest first.