OrderedDict.popitem
dict.popitem() can only take the newest item. OrderedDict.popitem(last=False) takes the oldest, which turns an OrderedDict into a keyed FIFO queue.
Common call
od.popitem(last=False)
Returns
('a', 1) — the first pair
Replaces
k = next(iter(d)); v = d.pop(k)
Watch out
empty: KeyError: 'dictionary is empty'
OrderedDict.popitem(lastlast — True: remove the last pair (LIFO). False: remove the first pair (FIFO).type: bool · default: True=True)
→ tuple[key, value]
Demo
Live evaluation
The default: pop the newest pair.
Try:
Inputs
keyslist[str]keys in order
Code
from collections import OrderedDict od = OrderedDict.fromkeys(['a', 'b', 'c'], 0) (od.popitem(), list(od))
Result
(('c', 0), ['a', 'b'])
The tuple is evaluated left to right, so list(od) already shows the OrderedDict without the popped key. On an empty OrderedDict the message is 'dictionary is empty' — a plain dict says 'popitem(): dictionary is empty'.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| last | bool | no (True) | True: remove the last pair (LIFO). False: remove the first pair (FIFO). |
Return value
tuple[key, value] — The removed pair.
Common patterns
Evict the oldest entry
Bounded cache: drop from the front when over capacity.
if len(cache) > capacity: cache.popitem(last=False)
Drain in insertion order
A keyed FIFO queue.
while od: key, value = od.popitem(last=False) handle(key, value)
Examples
1. Pop the last pair
from collections import OrderedDict
OrderedDict(a=1, b=2).popitem()
Returns
('b', 2)2. Pop the first pair
from collections import OrderedDict
OrderedDict(a=1, b=2).popitem(last=False)
Returns
('a', 1)3. last is also positional
from collections import OrderedDict
OrderedDict(a=1, b=2).popitem(False)
Returns
('a', 1)4. Empty OrderedDict
from collections import OrderedDict
OrderedDict().popitem()
Returns
KeyError: 'dictionary is empty'5. Plain dict: only the last
{'a': 1, 'b': 2}.popitem()
Returns
('b', 2)Pitfalls
1. Passing last=False to a plain dict
dict.popitem takes no arguments.
dict.popitem(last=False)
{'a': 1}.popitem(last=False)
TypeError: dict.popitem() takes no keyword arguments
next(iter(d))
d = {'a': 1, 'b': 2} k = next(iter(d)) (k, d.pop(k))
('a', 1)
2. Popping an empty OrderedDict in a loop
Guard with the truthiness of the dict.
no guard
from collections import OrderedDict od = OrderedDict(a=1) od.popitem() od.popitem()
KeyError: 'dictionary is empty'
while od:
from collections import OrderedDict od = OrderedDict(a=1) while od: od.popitem() len(od)
0
When to use
Use it
- FIFO eviction in caches
- Processing keyed items in arrival order
Reach for something else
- Only ever popping the last item → dict.popitem()
- A plain FIFO of values → deque.popleft()
Notes
CPython impl
OrderedDict_popitem_impl in Objects/odictobject.c
Errors
KeyError('dictionary is empty') on an empty OrderedDict
FAQ
With an OrderedDict: od.popitem(last=False). With a plain dict: k = next(iter(d)); v = d.pop(k) (raises StopIteration if d is empty).