How can I determine if a dictionary is empty?


#1

Question

Is it possible to determine whether a dictionary is empty?

Answer

Yes, there are several ways to check if a dictionary is empty. The more standard Python method is to use a Boolean evaluation on the dictionary. An empty dictionary (or other containers) will evaluate to a Boolean False. You can do that by testing just the dictionary variable or using the bool() function. Both methods are shown in the following code example.

dict1 = {}

if dict1:
    print("dict1 Not Empty")
else:
    print("dict1 is Empty")

if bool(dict1):
    print("dict1 Not Empty")
else:
    print("dict1 is Empty")

Also, it is possible to use the len() function to test whether the dictionary is empty. If it is empty, the function will return 0. This method is shown in the code example below.

dict1 = {}

if len(dict1) == 0:
    print("dict1 is Empty")