How to check if a dictionary is empty in python?

A dictionary is a built-in data type in python that contains data items as key-value pairs. A dictionary without any key-value pair is an empty dictionary. An empty dictionary is represented as {}. This article discusses different ways to determine if a dictionary is empty in python.

Checking if a dictionary is empty by using the len() function

The len() function calculates the number of key-value pairs present in the dictionary. If the length of the dictionary is 0, the dictionary is empty else the dictionary is not empty.

dict_1 = {1: "one", 2: "two", 3: "three"}
print("dict_1: ", dict_1)
print("Length of dict_1: ", len(dict_1))
if len(dict_1) == 0:
    print("dict_1 is Empty")
else:
    print("Not Empty")

The above code returns the output as

dict_1:  {1: 'one', 2: 'two', 3: 'three'}
Length of dict_1:  3
Not Empty

Checking if a dictionary is empty by using the bool function

An empty dictionary when passed to the bool() function returns False. The following example illustrates the use of the bool() function to determine if the dictionary is empty.

dict_1 = {}
print("dict_1: ", dict_1)
if bool(dict_1):
     print("dict_1 is not Empty")
else:
    print("dict_1 is Empty")​

Output

dict_1:  {}
dict_1 is Empty

Checking if a dictionary is empty by using the not operator

The not-operator returns a boolean value. An empty dictionary is evaluated to False in Python. Hence not-operator followed by an empty dictionary returns True.

Consider a dictionary, dict_1 = {}. If the dict_1 is empty the not operator returns a True Boolean value. Hence, if block is executed. If the dict_1 is not empty not-operator returns False which leads to execution of the else block.

dict_1 = {}
print("dict_1: ", dict_1)
if not dict_1:
    print("Empty dict_1")
else:
    print("dict_1 is not Empty")

The above code returns the output as Empty dict_1.

dict_1:  {}
Empty dict_1​

Checking if a dictionary is empty by comparing it with an empty dictionary

The dictionary is compared with an empty dictionary using the == operator. If the comparison returns True then the dictionary is empty. Otherwise, the dictionary is not empty.

dict_1 = {1: "one", 2: "two", 3: "three"}
print("dict_1: ", dict_1)
if dict_1 == {}:
    print("dict_1 is Empty")
else:
    print("Not Empty")

The above code gives the output as

dict_1:  {1: 'one', 2: 'two', 3: 'three'}
Not Empty
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions