Sometimes, we need to check if a particular dictionary is empty or not. In the 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 a database. Let’s discuss certain ways in which this task can be performed in Python.
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.
Python3
test_dict = {}
print ( "The original dictionary : " + str (test_dict))
res = not bool (test_dict)
print ( "Is dictionary empty ? : " + str (res))
|
Output :
The 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.
Python3
test_dict = {}
print ( "The original dictionary : " + str (test_dict))
res = not test_dict
print ( "Is dictionary empty ? : " + str (res))
|
Output:
The original dictionary : {}
Is dictionary empty ? : True
The time complexity of this program is O(1), as it involves a constant number of operations.
The auxiliary space complexity of this program is also O(1), as it only uses a constant amount of additional memory to store the dictionary and the result variable.
Check if a Dictionary is Empty using len()
Here, we are using the Python len() to check if the dictionary is empty or not.
Python3
test_dict = {}
print ( "The original dictionary : " + str (test_dict))
res = len (myDict) = = 0
print ( "Is dictionary empty ? : " + str (res))
|
Output:
The 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.
Python3
myDict = { 1 : 'Hello' , 2 : 'World' }
test_dict = {}
print ( "The original dictionary : " + str (myDict))
res = test_dict = = myDict
print ( "Is dictionary empty ? : " + str (res))
|
Output
The 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.
Python3
myDict = { 1 : 'Hello' , 2 : 'World' }
print ( "The original dictionary : " + str (myDict))
res = myDict.__len__() = = 0
print ( "Is dictionary empty ? : " + str (res))
|
Output
The original dictionary : {1: 'Hello', 2: 'World'}
Is dictionary empty ? : False
Time complexity: O(1)
Auxiliary Space: O(1)
Method: Using reduce():
Algorithm:
- 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.
Python3
from functools import reduce
test_dict = {}
print ( "The original dictionary : " + str (test_dict))
res = reduce ( lambda acc, x: False , test_dict, True )
print ( "Is dictionary empty ? : " + str (res))
|
Output
The original dictionary : {}
Is dictionary empty ? : True
Time complexity:
The time complexity of this code is O(n), where n is the number of key-value pairs in the dictionary. This is because the reduce method iterates over each key-value pair once, and the time taken to check for the presence of a single key-value pair is constant. Therefore, the time complexity grows linearly with the number of key-value pairs in the dictionary.
Space complexity:
The space complexity of this code is O(1), because it does not create any new data structures that grow with the size of the input. The only additional memory used is a few constant-sized variables to store the empty dictionary, the boolean result, and the lambda function used by reduce. Therefore, the space used by this code remains constant, regardless of the size of the input.
Using heapq:
Algorithm:
- 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.
Python3
import heapq
test_list = []
print ( "The original dictionary : " + str (test_list ))
res = not bool (heapq.nsmallest( 1 , test_list, key = lambda x: 0 ))
print ( "Is list empty? : " + str (res))
|
Output
The original dictionary : []
Is list empty? : True
Time Complexity: O(n log k), where n is the length of the list and k is the number of smallest elements to find (k=1 in this case). The nsmallest() method has a time complexity of O(n log k).
Space Complexity: O(k), where k is the number of smallest elements to find (k=1 in this case). The nsmallest() method creates a heap of size k.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Apr, 2023
Like Article
Save Article