We can easily check if a dictionary is empty in Python. An empty dictionary has length 0, and is equal to False, so to check if a dictionary is empty, we can just check one of these conditions.
empty_dict = {}
#length check
if len(empty_dict) == 0:
print("Dictionary is empty!")
#if statement check
if empty_dict:
print("Dictionary is empty!")
#comparing to empty dictionary
if empty_dict == {}:
print("Dictionary is empty!")
In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily determine if the dictionary is empty.
There are a few ways you can determine if a dictionary is empty.
Of course, you can always test to see if the dictionary is equal to another empty dictionary. Second, the length of an empty dictionary is 0. Finally, when converting an empty dictionary to a boolean value, we get False.
In this case, we can use any one of these conditions to determine if a dictionary is empty or not.
In the following Python code, you can see the three ways you ca check if a dictionary is empty or not.
empty_dict = {}
#length check
if len(empty_dict) == 0:
print("Dictionary is empty!")
#if statement check
if empty_dict:
print("Dictionary is empty!")
#comparing to empty dictionary
if empty_dict == {}:
print("Dictionary is empty!")
Checking if Dictionary is Empty with if Statement in Python
One fact we can use in Python to check if a dictionary is empty is that a dictionary that is empty is equivalent to the boolean value False.
In this case, we can test if a dictionary is empty using a simple if statement.
empty_dict = {}
#if statement check
if empty_dict:
print("Dictionary is empty!")
Checking if Dictionary is Empty Using Python len() Function
One of the ways we can easily check if a dictionary is empty in Python is with the Python len() function.
The length of a dictionary which is empty is 0.
Checking to see if a dictionary is empty using the Python len() function is shown in the following Python code.
empty_dictionary = {}
if len(empty_dictionary) == 0:
print("Dictionary is empty!")
Checking if Dictionary is Empty By Comparing to Another Empty Dictionary in Python
You can also check if a dictionary is empty by comparing it to another empty dictionary. This is the most obvious method and works if you want to check if a list is empty, or check if a set is empty.
Below is how to compare an empty dictionary to another dictionary to determine if the other dictionary is empty or not.
empty_dict = {}
if empty_dict == {}:
print("Dictionary is empty!")
Hopefully this article has been useful for you to learn how to check if a dictionary is empty in Python.