dict.popitem()
Removes the entry that was added last to a dictionary and returns it as a (key, value) pair. Raises KeyError when empty.
dict.popitem()popitem() takes out the most recently added entry and hands it back as a tuple (key, value). Calling it again and again empties the dictionary from the end, last in, first out.
Since Python 3.7 this order is guaranteed. (Very old Pythons removed an arbitrary entry, which is why older tutorials call it random.)
Changing the value of an existing key does not move it: "last added" means the key that was inserted last. On an empty dictionary popitem() raises KeyError, so check that the dictionary is not empty first.
Return value
A tuple (key, value) for the entry that was removed.
Examples
1Take the last entry
visits = {"home": 3, "shop": 1, "cart": 2}
print(visits.popitem())
print(visits)('cart', 2)
{'home': 3, 'shop': 1}2Unpack the pair
inbox = {"msg1": "Hello", "msg2": "Lunch?"}
key, text = inbox.popitem()
print(key, "->", text)msg2 -> Lunch?
3Empty a dictionary one entry at a time
jobs = {"print": 2, "scan": 1, "fax": 4}
while jobs:
name, pages = jobs.popitem()
print("Running", name, "-", pages, "pages")
print(jobs)Running fax - 4 pages
Running scan - 1 pages
Running print - 2 pages
{}4Updating a value does not change the order
d = {"a": 1, "b": 2}
d["a"] = 100
print(d.popitem())
d["z"] = 26
print(d.popitem())('b', 2)
('z', 26)Common mistakes
Calling popitem() on an empty dictionary
This raises KeyError. Loop with while d:, or check if d: first.
cache = {}
if cache:
print(cache.popitem())
else:
print("Nothing to remove")
try:
cache.popitem()
except KeyError:
print("KeyError: the dictionary is empty")Nothing to remove KeyError: the dictionary is empty
Using popitem() to remove a specific key
popitem() takes no arguments; it always removes the last entry. Use dict.pop() with the key to remove a particular one.
Questions people ask
Is dict.popitem() random?
No. Since Python 3.7 it always removes the most recently inserted entry.
How do I remove the first entry of a dictionary?
Get the first key and pop it: k = next(iter(d)); v = d.pop(k).
What is the difference between pop() and popitem()?
dict.pop() removes the key you name and returns its value. popitem() removes the last entry and returns both key and value.