How to check Python dictionary is empty?

Python dictionaries are one of the important data structures used in Python programming. Sometimes we might need to check whether the dictionary is empty or not. This article will discuss different ways to check whether the python dictionary is empty.

1. Using the len() function

We can check the length of any container using Python’s inbuilt len() function. The len() function returns the number of items in the dictionary. Here is an example to check dictionary empty or not :

my_dict = {}

if len(my_dict) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

In the above code, an empty dictionary(my_dict) is created. Then the length of the dictionary is checked using the if statement. If the length is zero it means it is an empty dictionary.

Output

Dictionary is empty

2. Using not operator

We can use the not operator to check if the dictionary is empty. If the dictionary is empty, its boolean value will be False in boolean context. This is the fastest method. Here’s an example:

my_dict = {}

if not my_dict:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output

Dictionary is empty

3. Using the bool() function

We can use the bool() function to check whether the dictionary is empty or not. See the below example :

my_dict = {}

if bool(my_dict) == False:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

The dictionary is passed to the bool function it will return false if the dictionary is empty.

Output

Dictionary is empty

4. Using the any() function

We can use the any() function to check if the dictionary is empty. If any key exists in the dictionary, it means the dictionary is not empty. Here’s an example:

my_dict = {}

if any(my_dict):
    print("Dictionary is not empty")
else:
    print("Dictionary is empty")

Output

Dictionary is empty

5. Using keys() function

We can use the keys() function to check if the dictionary is empty. If the dictionary has no keys, it means the dictionary is empty. Here’s an example:

my_dict = {}

if not my_dict.keys():
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output

Dictionary is empty

The fastest and most efficient way to check if a dictionary is empty in Python

We have seen many ways for dictionary empty check, so what is the fastest and most efficient way?

The not operator method is the fastest way to check dictionary is empty or not. This method is faster because it doesn’t require calling any functions or iterating through the dictionary. It simply checks the boolean value of the dictionary in a boolean context, which is a very fast operation.