my_dict = {}
if not my_dict:
print("Dictionary is empty")
Output
Dictionary is empty
This is the simplest and preferred method to check if a Python Dictionary is empty or not. We use the not keyword before the dictionary variable name and it will return true if the dictionary is empty and false if it is not empty.
Code example 1 - check for an empty dictionary
dict_a = {}
if not dict_a:
print("Dictionary is empty")
else:
print("Dictionary is not empty")
Output
Dictionary is empty
In the above code example:
Code example 2 - check for a dictionary that has properties
subject = {
"name": "Math",
"score": 90
}
if not subject:
print("Dictionary is empty")
else:
print("Dictionary is not empty")
Output
Dictionary is not empty
We know that the Python len() function is used to get the length of a dictionary or list. So we can use it to check if a dictionary contains any property or not. If the function returns 0 then the dictionary is empty else it has some properties in it.
my_dict = {}
if len(my_dict) == 0:
print("The dictionary is empty")
else:
print("The dictionary is not empty")
Output
The dictionary is empty
Explanation of the above code example
If we pass the dictionary variable to bool() function then it will return True if the dictionary is empty and False if the dictionary is not empty. So we will be using the not keyword with it to make it work as expected in the previous code examples.
my_dict = {}
if not bool(my_dict):
print("The dictionary is empty")
else:
print("The dictionary is not empty")
Output
The dictionary is empty
In the above code example
0 Comments