Python | Check if dictionary is empty
Sometimes, we need to check if a particular dictionary is empty or not. And this particular task has its application in 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 database. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using bool()
The bool function can be used to perform this particular task. As name suggests it performs the task of converting an object to a boolean value, but here, passing an empty string returns a False, as failure to convert something that is empty.
# Python3 code to demonstrate # Check if dictionary is empty # using bool() # 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)) |
The original dictionary : {}
Is dictionary empty ? : True
Method #2 : 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 code to demonstrate # Check if dictionary is empty # using not operator # 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)) |
The original dictionary : {}
Is dictionary empty ? : True
Recommended Posts:
- Python | Initializing dictionary with empty lists
- Python | Check whether a list is empty or not
- Python program to check if string is empty or not
- Python | Check if key has Non-None value in dictionary
- Python | Check if one dictionary is subset of other
- Python | Check if all values are 0 in dictionary
- Python | Check for None values in given dictionary
- Python | Check whether given key already exists in a dictionary
- Python dictionary, set and counter to check if frequencies can become same
- Python | Check if given multiple keys exist in a dictionary
- Python Dictionary | Check if binary representations of two numbers are anagram
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Convert string dictionary to dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



