Check if Python Dictionary is Empty (4 methods)

In this article, we will see how to check if Python dictionary is empty using different methods with some illustrative examples.

In Python, a dictionary is a built-in data type that can be used to store a mutable unordered collection of items. Each item stored in a dictionary has a key-value pair. Often, while writing code, it’s crucial to create an empty dictionary.

An empty dictionary can be created using curly braces{}, dict() constructor, or dictionary comprehension in Python. Also, sometimes we need to check if Python dictionary is empty before performing operations on it.

Methods to check if Python Dictionary is Empty

There are several methods to check if Python dictionary is empty.

  • By using if not operator
  • By using bool(dict) method
  • By using len() method
  • By using == operator

Let’s see them one by one using some demonstrative examples:

Method 1: Check if a dictionary is empty in Python using if not operator

In Python, you can check if a dictionary is empty using the if not operator. The if not operator reviews the boolean value of the object following it, and an empty dictionary evaluates to False in a boolean context. Therefore, using the if not with a dictionary will execute the block of code following it check if Python dictionary is empty.

Example: Let’s consider a scenario where we have a dictionary that holds the population of different states. And, we want to check if there is any data in the population dictionary or not.

Imagine you’re writing a program to analyze US state populations, but you only want it to execute if there’s data in the dictionary.

state_population = {}
if not state_population:
    print("No data available.")
else:
    print(f"Processing data: {state_population}")

Output: In this case, the output is “No data available.” because the state_population dictionary is empty.

No data available.
Python empty dictionary

This way we can use the if not operator to check if the dictionary is empty in Python or not.

Method 2: Use bool() function in Python to check if the dictionary is empty.

In Python, the bool() function is used to return the boolean value of a specified object. The bool() function returns True if the specified object has some content, and False if the object is empty.

When it comes to dictionaries, you can use the bool() function to check whether a Python dictionary is empty or not. An empty Python dictionary evaluates to False in a boolean context, while a non-empty dictionary evaluates to True.

For instance: Let’s say we are working with a system that keeps track of stock quantities for a bookstore. You want to check if a particular book is in stock or not.

The system returns a Python dictionary that represents the inventory for a specific book. If the dictionary is empty, it means the book is not in stock. If it has entries, the book is in stock, and the dictionary provides more details about it.

def check_book_stock(book_details):
    if not bool(book_details):
        return "The book is not in stock."
    else:
        return f"The book is in stock.\nDetails: {book_details}"

book_inventory_1 = {}
print(check_book_stock(book_inventory_1))

book_inventory_2 = {
    'title': 'To Kill a Mockingbird',
    'author': 'Harper Lee',
    'price': '$10.99',
    'quantity': 5
}
print(check_book_stock(book_inventory_2))

Output: In the first scenario (book_inventory_1), the dictionary is empty. Using the bool() function, it evaluates to False, implying that the book is not in stock.

In the second scenario (book_inventory_2), the dictionary contains details about the book, indicating that it’s in stock. When passed to the bool() function, the dictionary evaluates to True, and the function returns the book’s details. The output displays the book’s details, including its title, author, price, and quantity available in stock.

The book is not in stock.
The book is in stock.
Details: {'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'price': '$10.99', 'quantity': 5}
check if Python Dictionary is Empty

This way we can use the bool() function in Python to check if dictionary is empty.

Method 3: Dictionary is empty in Python check using len() function.

In Python, we can use the len() function to check if a dictionary is empty. The len() function returns the number of items (key-value pairs) in the dictionary. If the length of the dictionary is 0, then it means the dictionary is empty.

For example: Imagine you’re working on a system that manages voter registration data for a small county in the USA. You have a Python dictionary where the key is a voter’s name and the value is their registered address.

However, as you’re testing the system, you want to check whether there are any voters registered or if the Python dictionary is empty.

voter_data = {}
if len(voter_data) == 0:
    print("No voters have been registered yet.")
else:
    print(f"There are {len(voter_data)} registered voters.")

Output: The Python dictionary voter_data is empty. The len() function returns 0, indicating the dictionary has no items. Therefore, the output correctly states that no voters have been registered yet.

No voters have been registered yet.
Python dict is empty

This is how we can use len() to check if a dictionary is empty in Python.

Method 4: Check if a dictionary is empty in Python using the == operator.

In Python, we can check if a dictionary is empty (i.e., it contains no keys or values) by comparing it with an empty dictionary ({}) using the == operator. The == operator is used to compare the values of two objects and returns True if they are equal, and False otherwise.

For instance: Let’s consider a scenario, where we want to check whether a state has any registered vehicles. Let’s assume the vehicle registrations are stored in a dictionary in Python, where the keys are license plate numbers and the values are details about the vehicles. If the dictionary Python is empty, that means the state has no registered vehicles.

new_state_vehicle_registrations = {}
if new_state_vehicle_registrations == {}:
    print("The new state has no registered vehicles.")
else:
    print(f"The new state has {len(new_state_vehicle_registrations)} registered vehicles.")

Output: In this case, the new_state_vehicle_registrations dictionary in Python is empty. This way, by comparing the dictionary with {}, you can easily check if it is empty or not, and perform actions based on that.

The new state has no registered vehicles.
check if dict in Python is empty

This way we can use the == operator to check if the Python dictionary is empty.

Conclusion

This tutorial explains how to check if Python dictionary is empty using four different methods such as the if not operator, the bool() function, the len() function, and the == operator with demonstrative examples. The choice depends on the specific use case and the programmer’s preference. Whether it’s through direct Boolean checks or employing built-in functions, Python offers flexibility and efficiency in handling such tasks.

You may also like to read:


电子产品 排行榜


Gurmandise 哆啦A梦 铜锣烧 手机手环

IT電腦補習 java補習 為大家配對電腦補習,IT freelance, 私人老師, PHP補習,CSS補習,XML,Java補習,MySQL補習,graphic design補習,中小學ICT補習,一對一私人補習和Freelance自由工作配對。
立刻註冊及報名電腦補習課程吧!

facebook 查詢:
24 hours enquiry facebook channel :
https://www.facebook.com/itteacheritfreelance/?ref=aymt_homepage_panel

Be the first to comment

Leave a Reply

Your email address will not be published.


*