Open In App

Python | Check if dictionary is empty

Last Updated : 21 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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))


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




# 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))


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




# initializing empty dictionary
test_dict = {}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Check if dictionary is empty using len
res = len(myDict) == 0
 
# print result
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




# 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))


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




# 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


Output

The original dictionary : {1: 'Hello', 2: 'World'}
Is dictionary empty ? : False

Time complexity: O(1)

Auxiliary Space:  O(1)

Method: Using reduce():
Algorithm:
 

  1. Initialize an empty dictionary test_dict.
  2. Print the original dictionary.
  3. Use the reduce method to check if the dictionary is empty:
  4. Initialize the accumulator to True.
  5. Iterate over each key-value pair in the dictionary using reduce.
  6. Return False as soon as a key-value pair is encountered.
  7. If the iteration completes without finding any key-value pairs, return the initial value of the accumulator,
  8. which is True.
  9. Print the resulting boolean value.

Python3




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.


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:

  1. Import the heapq module.
  2. Initialize an empty list.
  3. Check if the list is empty using the nsmallest() method of the heapq module with k=1 and a custom key
  4. function that returns 0 for all elements.
  5. If the smallest element is not found, then the list is empty.
  6. Return the result.

Python3




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.


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads