Check if dictionary is empty in Python
Last Updated :
06 Oct, 2024
Sometimes, we need to check if a particular dictionary is empty or not.
Python
# initializing empty dictionary
d = {}
print(bool(d))
print(not bool(d))
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(bool(d))
print(not bool(d))
OutputFalse
True
True
False
Different Methods to Check if a Dictionary is Empty
Check if a Dictionary is Empty using bool()
The bool function can be used to perform this particular task. As the name suggests it performs the task of converting an object to a boolean value, but here, passing an empty string returns a False, as a failure to convert something that is empty.
Python
# 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))
OutputThe original dictionary : {}
Is dictionary empty ? : True
Check if a Dictionary is Empty 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.
Python
# 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))
OutputThe original dictionary : {}
Is dictionary empty ? : True
Check if a Dictionary is Empty using len()
Here, we are using the Python len() to check if the dictionary is empty or not.
Python
# initializing empty dictionary
d = {}
# printing original dictionary
print("The original dictionary : " + str(d))
# Check if dictionary is empty using len
res = (len(d) == 0)
# print result
print("Is dictionary empty ? : " + str(res))
OutputThe original dictionary : {}
Is dictionary empty ? : True
Check if a Dictionary is Empty using the Equality Operator
Here, we are comparing the dictionary with values with an empty dictionary to check if the dictionary is empty or not.
Python
# initializing empty dictionary
myDict = {1: 'Hello', 2: 'World' }
test_dict = {}
# printing original dictionary
print("The original dictionary : " + str(myDict))
# using operator
# Check if dictionary is empty
res = test_dict == myDict
# print result
print("Is dictionary empty ? : " + str(res))
OutputThe original dictionary : {1: 'Hello', 2: 'World'}
Is dictionary empty ? : False
Check if a Dictionary is Empty using the Using the not operator with the __len__() method:
This approach is similar to the previous one, but it uses the __len__() method instead of the len() function to get the length of the dictionary.
Python
# Initialize a dictionary with some key-value pairs
myDict = {1: 'Hello', 2: 'World' }
# Print the original dictionary
print("The original dictionary : " + str(myDict))
# Check if the dictionary is empty using the equality operator
res = myDict.__len__()==0
# Print the result
print("Is dictionary empty ? : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary : {1: 'Hello', 2: 'World'}
Is dictionary empty ? : False
Using reduce()
- Initialize an empty dictionary test_dict.
- Print the original dictionary.
- Use the reduce method to check if the dictionary is empty:
- Initialize the accumulator to True.
- Iterate over each key-value pair in the dictionary using reduce.
- Return False as soon as a key-value pair is encountered.
- If the iteration completes without finding any key-value pairs, return the initial value of the accumulator,
- which is True.
- Print the resulting boolean value.
Python
from functools import reduce
# initializing empty dictionary
test_dict = {}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# using reduce method to check if dictionary is empty
res = reduce(lambda acc, x: False, test_dict, True)
# print result
print("Is dictionary empty ? : " + str(res))
#This code is contributed by Rayudu.
OutputThe original dictionary : {}
Is dictionary empty ? : True
Using heapq:
- Import the heapq module.
- Initialize an empty list.
- Check if the list is empty using the nsmallest() method of the heapq module with k=1 and a custom key
- function that returns 0 for all elements.
- If the smallest element is not found, then the list is empty.
- Return the result.
Python
import heapq
# initialize empty list
test_list = []
# printing original dictionary
print("The original dictionary : " + str(test_list ))
# check if list is empty using heapq
res = not bool(heapq.nsmallest(1, test_list, key=lambda x: 0))
# print result
print("Is list empty? : " + str(res))
#This code is contributed by Rayudu.
OutputThe original dictionary : []
Is list empty? : True
Similar Reads
Check if Value Exists in Python Dictionary We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.Naive ApproachThis
2 min read
Check if a Key Exists in a Python Dictionary Python dictionary can not contain duplicate keys, so it is very crucial to check if a key is already present in the dictionary. If you accidentally assign a duplicate key value, the new value will overwrite the old one.To check if given Key exists in dictionary, you can use either in operator or get
4 min read
Check If a Nested Key Exists in a Dictionary in Python Dictionaries are a versatile and commonly used data structure in Python, allowing developers to store and retrieve data using key-value pairs. Often, dictionaries may have nested structures, where a key points to another dictionary or a list, creating a hierarchical relationship. In such cases, it b
3 min read
Python - Check for Key in Dictionary Value list Sometimes, while working with data, we might have a problem we receive a dictionary whose whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let's discuss certain ways in which this task can be performed. Method #1: Using any() Th
6 min read
Check If a Python Set is Empty In Python, sets are versatile data structures used to store unique elements. It's common to need to check whether a set is empty in various programming scenariosPython# Initializing an empty set s = set() print(bool(s)) # False since the set is empty print(not bool(s)) # True since the set is empty
2 min read