dict.popitem()
dict.popitem() tuple · Updated March 13, 2026 · Dict Methods The .popitem() method removes and returns the last key-value pair from the dictionary as a tuple. Since Python 3.7, dictionaries maintain insertion order, so .popitem() removes items in LIFO (last-in, first-out) order. This is useful when you need to process and remove dictionary entries sequentially.
Syntax
dict.popitem()
Parameters
None. This method takes no parameters.
Return Value
Returns a tuple containing the removed key-value pair: (key, value). If the dictionary is empty, raises a KeyError.
Basic Examples
Removing the last item
The most common use case is removing the last added item:
stack = {"first": 1, "second": 2, "third": 3}
item = stack.popitem()
print(item)
# ('third', 3)
print(stack)
# {'first': 1, 'second': 2}
Empty dictionary - KeyError
Calling .popitem() on an empty dictionary raises KeyError:
empty = {}
# This raises KeyError
# empty.popitem()
# Safe pattern - check if dict has items
if empty:
item = empty.popitem()
else:
print("Dictionary is empty")
# Dictionary is empty
Using in a loop
Process all items by repeatedly popping:
tasks = {"task1": "pending", "task2": "in-progress", "task3": "done"}
while tasks:
task_id, status = tasks.popitem()
print(f"Processing {task_id}: {status}")
# Processing task3: done
# Processing task2: in-progress
# Processing task1: pending
Practical Patterns
Stack implementation
Dictionaries can act as a stack when combined with .popitem():
class TaskQueue:
def __init__(self):
self._tasks = {}
self._counter = 0
def add(self, task):
self._counter += 1
self._tasks[self._counter] = task
def next(self):
if not self._tasks:
return None
return self._tasks.popitem()
queue = TaskQueue()
queue.add("build")
queue.add("test")
queue.add("deploy")
while True:
item = queue.next()
if item is None:
break
task_id, task = item
print(f"Executing {task_id}: {task}")
LRU cache implementation
A simple LRU cache using popitem for eviction:
class SimpleCache:
def __init__(self, maxsize=3):
self.maxsize = maxsize
self.cache = {}
def set(self, key, value):
if key in self.cache:
self.cache[key] = value
elif len(self.cache) >= self.maxsize:
# Remove oldest (first) item
self.cache.popitem()
self.cache[key] = value
def get(self, key):
return self.cache.get(key)
cache = SimpleCache(maxsize=2)
cache.set("a", 1)
cache.set("b", 2)
cache.set("c", 3) # Evicts 'a'
print(cache.get("a")) # None
print(cache.get("b")) # 2
Converting to ordered pairs
Sometimes you want to process pairs in reverse order:
data = {"x": 1, "y": 2, "z": 3}
# Process in reverse insertion order
reversed_data = []
while data:
reversed_data.append(data.popitem())
print(reversed_data)
# [('z', 3), ('y', 2), ('x', 1)]
pop() vs popitem()
| Method | Use Case |
|---|---|
.pop(key) | Remove a specific key by value |
.popitem() | Remove the last inserted key-value pair |
d = {"a": 1, "b": 2, "c": 3}
# pop() - specific key
val = d.pop("b")
print(val) # 2
# popitem() - last item
item = d.popitem()
print(item) # ('c', 3)
Performance Note
.popitem()is an O(1) operation - constant time- Unlike list.pop(), dictionary popitem doesn’t require shifting elements
- The LIFO behavior reflects insertion order (Python 3.7+)
- In Python versions before 3.7, order was implementation-dependent
See Also
- dict.pop() — remove a specific key by value
- dict.items() — iterate over key-value pairs without removing them
- dict() — the dict constructor for creating new dictionaries