Last modified: Jan 10, 2023 By Alexander Williams
How to Properly Check if a Dictionary is Empty in Python
In this article, we'll show you the good and the worst way to check if a list is empty.
checking if a dictionary is empty [the good way]
Example 1
#dictionary
dictionary = {}
#check if the dictionary is empty
if not dictionary:
print('the Dictionary is empty.')
else:
print('the Dictionary is not empty.')
output
the Dictionary is empty.
Example 2
#dictionary
dictionary = {"key":"val", "key":"val"}
#check if the dictionary is empty
if not dictionary:
print('the Dictionary is empty.')
else:
print('the Dictionary is not empty.')
output
the Dictionary is not empty.
example 2: checking if a dictionary is empty [the worst way]
Example 1
#dictionary
dictionary = {}
#check if the dictionary is empty
if len(dictionary) == 0:
print('the Dictionary is empty.')
else:
print('the Dictionary is not empty.')
output
the Dictionary is empty.
Example 2
#dictionary
dictionary = {"key":"val", "key":"val"}
#check if the dictionary is empty
if len(dictionary) == 0:
print('the Dictionary is empty.')
else:
print('the Dictionary is not empty.')
output
the Dictionary is not empty.
in the examples above, we have checked the dictionary by using len() built-in function, it's working but in python, we don't need to use len() to check empty variables, list, dictionary, tuple.