Skip to content
Related Articles

Related Articles

Python | Check if dictionary is empty

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 29 Sep, 2022
View Discussion
Improve Article
Save Article

Sometimes, we need to check if a particular dictionary is empty or not. In the web development domain in which we sometimes need to test for results of a particular query or check whether we have any key to add info into a database. Let’s discuss certain ways in which this task can be performed in Python

Check if a Dictionary is Empty using bool()

The bool function can be used to perform this particular task. As the name suggests it performs the task of converting an object to a boolean value, but here, passing an empty string returns a False, as a failure to convert something that is empty. 

Python3




# initializing empty dictionary
test_dict = {}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# using bool()
# Check if dictionary is empty
res = not bool(test_dict)
 
# print result
print("Is dictionary empty ? : " + str(res))


Output :

The original dictionary : {}
Is dictionary empty ? : True

Check if a Dictionary is Empty using not operator 

This task can also be performed using the not operator that checks for a dictionary existence, this evaluates to True if any key in the dictionary is not found. 

Python3




# initializing empty dictionary
test_dict = {}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# using not operator
# Check if dictionary is empty
res = not test_dict
 
# print result
print("Is dictionary empty ? : " + str(res))


Output:

The original dictionary : {}
Is dictionary empty ? : True

Check if a Dictionary is Empty using len()

Here, we are using the Python len() to check if the dictionary is empty or not.

Python3




# initializing empty dictionary
test_dict = {}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Check if dictionary is empty using len
res = len(myDict) == 0
 
# print result
print("Is dictionary empty ? : " + str(res))


Output:

The original dictionary : {}
Is dictionary empty ? : True

Check if a Dictionary is Empty using the Equality Operator

Here, we are comparing the dictionary with values with an empty dictionary to check if the dictionary is empty or not.

Python3




# initializing empty dictionary
myDict = {1: 'Hello', 2: 'World' }
test_dict = {}
 
# printing original dictionary
print("The original dictionary : " + str(myDict))
 
# using operator
# Check if dictionary is empty
res = test_dict == myDict
 
# print result
print("Is dictionary empty ? : " + str(res))


Output

The original dictionary : {1: 'Hello', 2: 'World'}
Is dictionary empty ? : False

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!