How to Check If a Dictionary is Empty in Python

To check if a dictionary is empty in Python, you can use an if statement, the not operator with the bool() function, or the len() function.

The following examples show how to check if a dictionary is empty in Python.

Using if Statement

We can use an if statement to check if a dictionary is empty.

Suppose we have the following dictionary:

# Declare dictionary
dict1 = {}

# Check if the dictionary is empty
if dict1:
    print("dict1 is not empty")
else:
    print("dict1 is empty")

Output: 👇️

dict1 is empty

In this example, we use an if statement to check if dict1 is empty. The condition if dict1 evaluates to False if the dictionary is empty.

Using not Operator & bool() Function

We can use the not operator with the bool() function to check if a dictionary is empty.

Suppose we have the following dictionary:

# Declare dictionary
dict1 = {}

# Check if the dictionary is empty
if not bool(dict1):
    print("dict1 is empty")
else:
    print("dict1 is not empty")

Output: 👇️

dict1 is empty

In this example, we use the not operator with the bool() function to check if dict1 is empty. The condition if not bool(dict1) evaluates to True if the dictionary is empty.

Using len() Function

We can use the len() function to check if a dictionary is empty.

Suppose we have the following dictionary:

# Declare dictionary
dict1 = {}

# Check if the dictionary is empty
if len(dict1) == 0:
    print("dict1 is empty")
else:
    print("dict1 is not empty")

Output: 👇️

dict1 is empty

In this example, we use the len() function to check if the length of dict1 is 0, indicating that the dictionary is empty.

Conclusion

We can use an if statement, the not operator with the bool() function, and the len() function to check if a dictionary is empty in Python.