Python - Check if dictionary is empty


During analysis of data sets we may come across situations where we have to deal with empty dictionaries. In tis article we will see how to check if a dictionary is empty or not.

Using if

The if condition evaluates to true if the dictionary has elements. Otherwise it evaluates to false. So in the below program we will just check the emptiness of a dictionary using only the if condition.

Example

 Live Demo

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
if dict1:
   print("dict1 is not empty")
else:
   print("dict1 is empty")
if dict2:
   print("dict2 is not empty")
else:
   print("dict2 is empty")

Output

Running the above code gives us the following result −

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
dict1 is not empty
dict2 is empty

Using bool()

The bool method evaluates to true if the dictionary is not empty. Else it evaluates to false. So we use this in expressions to print the result for emptiness of a dictionary.

Example

 Live Demo

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
print("Is dict1 empty? :",bool(dict1))
print("Is dict2 empty? :",bool(dict2))

Output

Running the above code gives us the following result −

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
Is dict1 empty? : True
Is dict2 empty? : False

Updated on: 03-Mar-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements