How to check if a dictionary is empty in Python

The dictionary is an unordered collection of items that stores the data in the form of key-value pairs. Dictionaries are very useful data structures when the data has a unique reference, especially in database management. When working with databases, you often need to determine if a dictionary is empty before inserting or updating records. An empty dictionary might indicate that no data needs to be added or updated. In web development, there are situations where we need to verify the presence of keys before adding information to the database. In such cases, it’s important to check whether a dictionary is empty or not.

Python provides several methods, with commonly used ones being len() and bool() to check if a dictionary is empty or not. However, there are numerous other approaches to accomplish this task, and we’ll explore them all in this comprehensive guide.

use if-else to determine if a dictionary is empty in Python

The fundamental approach to check if a dictionary is empty is to use if-else statements. If the dictionary has elements, then the if-condition will become true and the statements inside the if-block will get executed. You can display a message inside the if and else block stating whether the dictionary is empty or not. Let’s illustrate this with an example provided below.

# Using IF-ELSE Method

fruits= {}

#Check if the dictionary is empty or not
if fruits:

   print("Dictionary of fruits is not empty")

else:

   print("Dictionary of fruits is empty")
Output:
Dictionary of fruits is empty

The above program checks whether the dictionary is empty or not. If the dictionary is empty, the if condition becomes true and the program will print a message that “dictionary is empty”; otherwise the program will display a message stating that it’s “not empty”.

In the above example, the dictionary of fruits is empty. Therefore, the compiler will execute statements inside the else block. For a better understanding of if-else statements, read this article.

You can also use a not operator with an if statement, as shown in the example below. Now, if the dictionary is empty, the compiler will execute if block. This code will behave opposite to the previous example.

fruits= {}

#Check if the dictionary is empty or not
if not fruits:

   print("Dictionary of fruits is empty")

else:

   print("Dictionary of fruits is not empty")
Output:
Dictionary of fruits is empty

Both of these programs are quite similar. In Example 1, the else block is executed when the dictionary is empty, while in Example 2, the if-block is executed when the dictionary is empty. The choice between these methods depends on your preference for readability and the specific logic of your program.

Use Bool() Function to check if a dictionary is empty or not

You can also use a bool function to check whether the dictionary is empty or not. When applied to a dictionary, the bool() function returns True if the dictionary has elements (i.e., it’s not empty) and False if the dictionary is empty.

In this code, we first create two dictionaries, ‘books’ and ‘fruits’. We then use the bool() function to check if each dictionary is empty or not and print the results.

# Creating a dictionary 'books' with key-value pairs
books = {1: "Science", 2: "Mathematics", 3: "English", 4: "Arts"}

# Creating an empty dictionary 'fruits'
fruits = {}

# Checking if 'books' is empty using the bool() function
print(bool(books))  

# Checking if 'fruits' is empty using the bool() function
print(bool(fruits))
Output:
True
False

You can also use a bool function to check along with if-else statements. Here, the bool() function will evaluate the condition. If the condition is satisfied, the bool() function returns True and executes all the statements inside the if-block. If the Boolean expression evaluates to False, the else block will be executed.

# Create a dictionary of books
books = {1: "Science", 2: "Mathematics", 3: "English", 4: "Arts"}

# Check if the dictionary is empty
if bool(books):
    print("Dictionary of books is not empty")
else:
    print("Dictionary of books is empty")
Output:
Dictionary of books is not empty

You can reverse the above logic using not operator to check if a dictionary is empty. In this case, You can use the bool() function returns false for an empty sequence and true for non-empty sequence.

# Create a dictionary of books
books = {1: "Science", 2: "Mathematics", 3: "English", 4: "Arts"}

# Check if the dictionary is empty
if not bool(books):
    print("Dictionary of books is empty")
else:
    print("Dictionary of books is not empty")
  
Output:
Dictionary of books is not empty

The bool() function allows you to check the dictionary if it is empty or not. This approach is efficient and suitable for cases where you only need a binary result to determine if the dictionary has any key-value pairs.

use len() function to Determine if a dictionary is empty

Another possible method is to use the len() function. The len() function provides a straightforward way to determine if a dictionary is empty by examining its length. You can determine whether a dictionary includes key-value pairs by comparing its length to zero. If the dictionary is empty, its length would be zero, and the len() function would return 0.

The following example shows how to determine whether the list is empty or not using the len() function.

# Creating a dictionary of product prices
product_prices = {
    'Laptop': 1000,
    'Smartphone': 500,
    'Tablet': 300,
    'Headphones': 50,
    'Mouse': 20
}

# Checking if the dictionary is empty by using the len() function
if len(product_prices) == 0:
    print("Dictionary of Product prices is empty")
else:
    print("Dictionary of Product prices is not empty")
Output:
Dictionary of Product prices is not empty

In the code above, we created a dictionary of product prices and then used the len() function to check if the dictionary is empty based on its length. Depending on the result, the program prints a corresponding message.

Using the any() function to check if dictionary is empty

The any() function in Python takes an iterable (such as a list, tuple, dictionary, etc.) as an argument and returns a Boolean value. It returns True if any element or item in the iterable is true, and False if all items in the iterable are false. It can also be used to check if an iterable is empty. For an empty iterable, the any() function returns False. Therefore, you can determine whether a dictionary is empty or not using the any() function. It’s important to note that the any() function will return False for an empty dictionary.

# Using the any() function to check if the dictionary is empty or not

emptydictionary = {}

if any(emptydictionary):
    print('This dictionary is not empty')
else:
    print('This dictionary is empty')
Output:
The dictionary is empty

This code will check if there are any items in the dictionary. If there are, it will print “This dictionary is not empty.” Otherwise, it will print “This dictionary is empty.”

Using the keys to check if the dictionary is empty or not

You can use Python’s built-in keys() method to check if a dictionary is empty or not. The keys() method returns a view object that displays a list of all the keys in the dictionary. When the dictionary is empty, keys() will also be empty, and Python treats empty sequences as False when used in a boolean context. Therefore, if not days.keys() is True for an empty dictionary and False for a non-empty dictionary.

Consider an example to understand how you can use keys to check if dictionary is empty or not. In this code, we create a dictionary days with key-value pairs representing days of the week. We then use the keys() method to get a view object of the keys in the dictionary.

# Create a dictionary of days
days = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'}

# Check if the dictionary is empty using the keys() method
if not days.keys():
    print("The dictionary is empty")
else:
    print("The dictionary is not empty")
Output:
The dictionary is not empty

In the above code, if not days.keys() condition checks if the view object is empty. If it’s empty, it means the dictionary is empty, and the corresponding message is printed. Otherwise, it prints that the dictionary is not empty.

Conclusion

You often come up with situations where you have to perform a certain operation on dictionaries. Before performing the operation, you first need to check whether the dictionary is empty or not. If the dictionary is empty, then initialize it first otherwise, perform the desired operation. This article discussed different ways to check whether the dictionary is empty or not. If you have any queries regarding this article, contact us. Your feedback would be highly appreciated.

Leave a Comment

Your email address will not be published. Required fields are marked *