How to Check if a Dictionary is Empty in Python
In Python, you frequently need to determine if a dictionary has any key-value pairs. An empty dictionary ({}) is considered "falsy" in a boolean context, a core concept in Python that leads to a very clean and readable way to perform this check.
This guide will cover the three main methods for checking if a dictionary is empty, with a strong recommendation for the idiomatic "truthiness" check, and will clarify the nuances of each approach.
Understanding Truthiness in Python
In Python, every object has an inherent boolean value. An object is considered "truthy" if it evaluates to True and "falsy" if it evaluates to False. This is fundamental to writing concise Python code.
For dictionaries:
- Falsy: An empty dictionary (
{}). - Truthy: Any non-empty dictionary (e.g.,
{'key': 'value'}).
Other common falsy objects include None, 0, empty strings (""), and other empty collections like [] and ().
Method 1: Check the Dictionary's Truthiness (Most Pythonic)
The most common, readable, and recommended way to check for an empty dictionary is to use the dictionary object directly in a conditional statement. This leverages the concept of truthiness.
To check if a dictionary is empty: use if not my_dict:. This is the standard, idiomatic pattern.
empty_dict = {}
if not empty_dict:
print("The dictionary is empty.")
else:
print("The dictionary is not empty.")
Output:
The dictionary is empty.
To check if a dictionary is not empty: use if my_dict:.
non_empty_dict = {"name": "Tom"}
if non_empty_dict:
print("The dictionary is not empty.")
else:
print("The dictionary is empty.")
Output:
The dictionary is not empty.
Method 2: Compare Length with len()
You can also determine if a dictionary is empty by checking its length. The len() function returns the number of key-value pairs. An empty dictionary has a length of 0.
Solution:
my_dict = {}
if len(my_dict) == 0:
print("The dictionary is empty.")
else:
print("The dictionary is not empty.")
Output:
The dictionary is empty.
While this code is perfectly functional and explicit, the truthiness check (if not my_dict) is generally preferred by the Python community for being more concise and just as readable.
Method 3: Compare with an Empty Dictionary Literal ({})
A third method is to directly compare your variable to an empty dictionary literal ({}) using the equality operator (==).
Solution:
my_dict = {}
if my_dict == {}:
print("The dictionary is empty.")
else:
print("The dictionary is not empty.")
Output:
The dictionary is empty.
Some might argue this is the "best" check because it is very specific. However, if not my_dict is the overwhelmingly standard idiom for checking for "emptiness" on any collection in Python, not just dictionaries. A variable named my_dict holding a value like True (which is truthy but not a dictionary) would indicate a different kind of logic error in the code. For its intended purpose, the truthiness check is the most Pythonic and widely understood method.
Conclusion
While there are multiple ways to check if a Python dictionary is empty, the community has a strong preference for one method due to its readability and conciseness.
- Recommended / Most Pythonic: Use the dictionary's truthiness (
if not my_dict:). It's the standard idiom for all collection types in Python. - Explicit Alternative: Compare its length to zero (
if len(my_dict) == 0:). - Literal Alternative: Compare it to an empty dictionary literal (
if my_dict == {}:).
For writing clean, maintainable, and idiomatic Python, the truthiness check is the best practice.