KeyError: popitem(): dictionary is empty (Fix)
Fix the Python error "KeyError: popitem(): dictionary is empty". This error happens when you call popitem() on a dictionary that has no items left.
This page explains what the error means, shows a small example that causes it, and gives simple ways to avoid it.
Quick fix #
Check that the dictionary is not empty before calling popitem():
data = {}
if data:
key, value = data.popitem()
else:
print("Dictionary is empty")
An empty dictionary is False, so if data: is a simple way to avoid this error.
What this error means #
popitem() is a dictionary method that removes and returns one key-value pair.
If the dictionary is empty, there is nothing to remove. Python raises:
KeyError: 'popitem(): dictionary is empty'
If you are new to dictionaries, see Python dictionaries explained.
Example that causes the error #
This code creates an empty dictionary and then calls popitem() on it:
data = {}
data.popitem()
Output:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyError: 'popitem(): dictionary is empty'
Why this fails:
datais{}, which means it has no key-value pairspopitem()tries to remove one pair- There is nothing to remove, so Python raises
KeyError
If you want to learn more about how this method works, see the Python dictionary popitem() method.
Why it happens #
This error usually happens for one of these reasons:
- The dictionary started empty
- Items were removed earlier in the program
- A loop kept calling
popitem()after the dictionary became empty - You expected data from another function, but it returned an empty dictionary
Here is a common loop mistake:
data = {"a": 1}
while True:
print(data.popitem())
This removes the only item first. On the next loop, the dictionary is empty, so the error happens.
How to fix it #
There are a few simple ways to fix this error.
Check if the dictionary has items #
This is the clearest fix for beginners:
data = {"name": "Alice"}
if data:
item = data.popitem()
print(item)
else:
print("Dictionary is empty")
Output:
('name', 'Alice')
if data: works because:
- non-empty dictionaries are
True - empty dictionaries are
False
Use an explicit length check #
If you want to be more explicit, use len():
data = {}
if len(data) > 0:
print(data.popitem())
else:
print("Dictionary is empty")
This does the same thing, but if data: is shorter and more common.
Use try-except when empty dictionaries are expected #
Sometimes an empty dictionary is normal in your program. In that case, you can catch the error:
data = {}
try:
key, value = data.popitem()
print(key, value)
except KeyError:
print("Dictionary is empty")
This works, but for beginners, an if check is usually easier to read.
Review earlier code #
Sometimes popitem() is not the real problem. The real issue is that the dictionary became empty earlier.
For example:
data = {"x": 1, "y": 2}
data.clear()
data.popitem()
data.clear() removes everything, so popitem() fails after that.
If you are removing a specific key instead of an arbitrary item, see how to remove a key from a dictionary in Python.
Recommended beginner-safe pattern #
The safest pattern is:
- Check whether the dictionary is empty
- Use
popitem()only when there is at least one item - Handle the empty case with a message, return value, or different logic
Example:
def remove_one_item(data):
if data:
return data.popitem()
return None
info = {}
result = remove_one_item(info)
print(result)
Output:
None
This is usually clearer than relying on exceptions for normal program flow.
Debugging steps #
If you are not sure why the error is happening, inspect the dictionary right before popitem().
Useful checks:
print(my_dict)
print(len(my_dict))
print(bool(my_dict))
print(my_dict.keys())
What these show:
print(my_dict)shows the full dictionaryprint(len(my_dict))shows how many items it hasprint(bool(my_dict))showsFalsewhen it is emptyprint(my_dict.keys())shows the current keys
You can also:
- Print the dictionary right before
popitem() - Trace where items are removed earlier
- Check whether
clear(),pop(), or anotherpopitem()emptied it - If using a loop, make sure the loop stops when the dictionary becomes empty
A safe loop looks like this:
data = {"a": 1, "b": 2}
while data:
print(data.popitem())
print("Done")
Output:
('b', 2)
('a', 1)
Done
Common mistakes #
These are common causes of this error:
- Calling
popitem()on{} - Using
popitem()inside awhileloop without checking if items remain - Removing all dictionary items earlier with
clear(),pop(), orpopitem() - Assuming loaded or returned data is non-empty when it is actually empty
If you are dealing with a broader dictionary key problem, see KeyError in Python: causes and fixes.
If your code depends on checking for a key before removing or reading it, see how to check if a key exists in a dictionary in Python.
FAQ #
What does popitem() return? #
It returns one key-value pair as a tuple, like ('name', 'Alice').
Why is this a KeyError? #
Because popitem() tries to remove a dictionary key, but there is no key to remove.
How do I check if a dictionary is empty? #
Use if my_dict:. An empty dictionary is False.
Should I use try-except or an if check? #
For beginners, an if check is usually simpler and easier to read.
See also #
- Python dictionaries explained
- Python dictionary
popitem()method - How to remove a key from a dictionary in Python
- How to check if a key exists in a dictionary in Python
- KeyError in Python: causes and fixes
To prevent this error next time, learn how dictionaries work and use popitem() only when you know the dictionary still has items.