When we are working with dictionaries in Python, we often need to check if the dictionary is empty. There are several methods which we can use to check if the dictionary is empty.
There is a very simple rule in Python that an empty dictionary or any other container(list, tuple, set, etc) always evaluates to a Boolean False value. We can take help of this statement to check if the dictionary is empty.
This can be done in two ways. First, by directly using the name of the dictionary with the if statement as given below:
empty_dict = {} if empty_dict: print('Dictionary is not empty!') else: print('Dictionary is empty!')
Output:
Dictionary is empty!
Second, we can use the inbuilt bool()
function. The bool()
function will return a Boolean True if the dictionary is not empty, otherwise, it will return a Boolean False.
Here is the code:
empty_dict = {} empty_val = bool(empty_dict) # Returns False if empty_val: print('Dictionary is not empty!') else: print('Dictionary is empty!')
Output:
Dictionary is empty!
Using the len() function to check if a dictionary is empty
There is one more easy way to check if a dictionary is empty or not. The len() function.
The len()
function always returns 0 if the dictionary is empty, otherwise, it returns a non-zero value.
empty_dict = {} length = len(empty_dict) if length==0: print('Dictionary is empty!') else: print('Dictionary is not empty!')
Output:
Dictionary is empty!