Check if Dictionary is Empty
Python - Check if Dictionary is Empty
To check if Python Dictionary is empty, you can write a condition that the length of the dictionary is zero or use not operator along with dictionary to form a boolean condition.
The condition not dict will return True if the the dictionary is empty and False if the dictionary is not empty.
The other way to check if the dictionary is empty, is checking if there are zero key:value pairs in the dictionary. Call builtin len() function and pass the dictionary as argument. len() function returns an integer representing the number of key:value pairs in the dictionary. If the dictionary is empty, len() returns 0.
The boolean condition to check if the dictionary is empty is
len(myDict) == 0
We will use this condition in a Python If statement, in the following examples.
Examples
1. Check if given Dictionary is empty using not Operator
In the following program, we will create an empty dictionary, and check programmatically if the dictionary is empty or not using not operator.
Python Program
myDict = {}
if not myDict:
print('The dictionary is empty.')
else:
print('The dictionary is not empty.')
Output
The dictionary is empty.
2. Check if Dictionary is empty using len()
In the following program, we will use len() builtin function to check if the dictionary is empty or not.
Python Program
myDict = {}
if (len(myDict) == 0):
print('The dictionary is empty.')
else:
print('The dictionary is not empty.')
Output
The dictionary is empty.
len(dict) == 0
returns True and therefore Python executes if block block.
3. Check if given Dictionary is empty [Negative Scenario]
In this example, we will initialize a dictionary with some key:value pairs, and check programmatically if the dictionary is empty or not. The condition to check if the dictionary is empty should return false, and execute else block.
Python Program
myDict = {'a':'apple', 'b':'banana', 'c':'cherry'}
if (len(myDict) == 0):
print('The dictionary is empty.')
else:
print('The dictionary is not empty.')
Output
The dictionary is not empty.
Summary
In this tutorial of Python Examples, we learned how to check if a Python Dictionary is empty or not.