Python Dictionary popitem() Method
dict.popitem() removes the most recently inserted key-value pair from a dictionary and returns it as a (key, value) tuple. On an empty dictionary it raises KeyError.popitem() is handy when you do not care which key you remove, only that the dictionary shrinks: processing items until none are left, or undoing the latest addition. Unlike dict.pop(), you do not name a key.
Since Python 3.7 dictionaries remember insertion order, and popitem() is documented to return pairs in LIFO order: last in, first out. In Python 3.6 and earlier the pair removed was arbitrary. See also the lesson on dictionary methods.
| Syntax | my_dict.popitem() |
|---|---|
| Parameters | None |
| Returns | A (key, value) tuple of the last inserted pair |
| Empty dictionary | Raises KeyError |
| Time complexity | O(1) |
How popitem() picks the pair to remove
The pair removed is always the one inserted most recently. Updating the value of an existing key does not move it; only a newly added key goes to the end. After the call the pair is gone from the dictionary.
d = {"a": 1, "b": 2, "c": 3}
print(d.popitem())
print(d)
d["a"] = 10
print(d.popitem())The second call removes "b", not "a", because changing the value of "a" did not make it the newest key.
Emptying a dictionary with a popitem() loop
Because popitem() raises KeyError on an empty dictionary, loop with while d:. An empty dictionary is falsy, so the loop stops by itself. This pattern is useful as a work queue or stack where each processed item is removed. If you simply want to remove everything without looking at it, use clear().
popitem() compared with pop() and del
Examples you can run
Press Run, then edit the code and run it again.
Undo the latest entry
Each call returns the newest pair as a tuple, which you can unpack.
history = {"step1": "open", "step2": "edit", "step3": "save"}
key, value = history.popitem()
print(key, value)
print(history)Expected outputstep3 save
{'step1': 'open', 'step2': 'edit'}
Process every item until the dictionary is empty
while tasks: is true while the dictionary has entries.
tasks = {"mail": 2, "report": 5, "call": 1}
while tasks:
name, hours = tasks.popitem()
print(f"done {name} ({hours}h)")
print(tasks)Expected outputdone call (1h)
done report (5h)
done mail (2h)
{}
popitem() on an empty dictionary
Catch the KeyError if the dictionary can legitimately be empty.
d = {}
try:
d.popitem()
except KeyError as e:
print("KeyError:", e)Expected outputKeyError: 'popitem(): dictionary is empty'
Common mistakes
Passing a key to popitem()
✗ Wrong
d = {"a": 1}
d.popitem("a")✓ Right
d = {"a": 1}
print(d.pop("a"))popitem() takes no arguments. To remove a specific key use d.pop("a").
Assuming it removes the first item
✗ Wrong
d = {"first": 1, "last": 2}
print(d.popitem())✓ Right
d = {"first": 1, "last": 2}
print(d.pop(next(iter(d))))To remove the oldest pair use d.pop(next(iter(d))).
Python Dictionary popitem() Method: questions people ask
What does popitem() do in Python?
It removes the last inserted key-value pair from the dictionary and returns it as a tuple.
Does popitem() remove a random item?
Not in modern Python. Since 3.7 it removes the most recently inserted pair (LIFO). Before 3.7 the order was arbitrary.
How do I remove the first item of a dictionary?
Use d.pop(next(iter(d))). popitem() removes the last item, not the first.
Keep learning
Step-by-step lessons:
Python DictionariesPython Dictionary Methods
Related:
Python Dictionary pop() MethodPython Dictionary clear() MethodPython Dictionary items() MethodPython Dictionary update() Method
More in dictionary methods:
Python Dictionary get() MethodPython Dictionary items() MethodPython Dictionary keys() MethodPython Dictionary values() MethodPython Dictionary update() MethodPython Dictionary pop() MethodPython Dictionary setdefault() MethodPython Dictionary clear() Method See all →