How to Check if a Dictionary is Empty in Python (2023)

Dictionaries are a critical data structure in Python used to store data as key-value pairs. They are mutable, unordered, and widely used in all types of Python code. It’s very common when working with dictionaries in Python to need to check if a dictionary is empty or contains elements. Testing for emptiness is useful for…

By.

min read

Dictionaries are a critical data structure in Python used to store data as key-value pairs. They are mutable, unordered, and widely used in all types of Python code.

It’s very common when working with dictionaries in Python to need to check if a dictionary is empty or contains elements. Testing for emptiness is useful for conditional logic in your code.

In this article, we’ll cover several ways to check if a dictionary is empty or not in Python:

  • Check dictionary length
  • Convert dictionary to bool
  • Use len() function
  • Check for presence of keys
  • Check for presence of values
  • Check keys and values together

Let’s look at each approach in detail with examples.

Check Dictionary Length to Test Emptiness

The easiest and most Pythonic way to check if a dictionary is empty is to check its length property.

The built-in len() function returns the length of a dictionary, which is the number of items it contains. An empty dictionary has a length of 0.

Here’s an example:

my_dict = {}

if len(my_dict) == 0:
  print("The dictionary is empty")

This directly checks the number of key-value pairs in the dictionary. If its length is 0, we know it’s empty.

The length property is very fast and efficient to test emptiness. It’s usually the best approach.

Convert Dictionary to bool to Check Emptiness

Another way in Python is to convert the dictionary to a boolean directly using the bool() function or by just putting it in a conditional.

An empty dictionary evaluates to False when converted to a boolean, while a non-empty dictionary becomes True.

Here’s how it looks:

my_dict = {}

if not my_dict:
   print("The dictionary is empty")

This works because an empty dictionary is considered falsey in Python. The if statement checks for the “falsy-ness” to check if it’s empty.

The bool conversion approach is more explicit than checking the length but not as efficient. Still, it can be nice for quick tests on small dictionaries.

Use len() Function to Get Length

We can also use the len() function directly instead of the length property to get the number of items:

my_dict = {}

if len(my_dict) == 0:
  print("The dictionary is empty")

This gives the same result but by calling len() instead of accessing the length property directly.

There isn’t much advantage to using len() here versus the length property. It’s slightly less efficient since it has to call a function first.

So in summary, for checking dictionary emptiness, use the length property when possible for best performance and conciseness. The len() function or bool conversion work fine too.

Check for Presence of Keys to Test Emptiness

Another approach to test for an empty dictionary is to check if it contains any keys.

A dictionary with keys is not empty, so we can check for the presence of keys to indirectly test for emptiness.

The in operator lets us check if a key is present in a concise way:

my_dict = {}

if "test" in my_dict:
  print("Dictionary contains keys")
else: 
  print("Dictionary is empty")

This works because the in operator does membership testing and returns True if the key is present in the dictionary.

For an empty dictionary, it will always return False. So we can use the presence of any key to infer that the dictionary is not empty.

Another way without the in operator is to use the dict.keys() method:

my_dict = {}

if len(my_dict.keys()) == 0:
   print("Dictionary is empty")
else:
   print("Dictionary contains keys")

The keys() method returns a view object containing all the keys that we can check the length of. If the length is 0, there are no keys.

In most cases, I recommend using the in operator for simplicity. The keys() approach makes more sense if you need to iterate through the keys for some reason.

This gives us another tool in our toolkit to indirectly check emptiness by looking for any keys. Next let’s look at a similar technique for values.

Check for Presence of Values to Test Emptiness

Similar to checking for keys, we can also test if a dictionary is empty by looking for any values.

If a dictionary contains any values, then we know it’s not empty:

my_dict = {}

if "test" in my_dict.values():
  print("Dictionary contains values")
else:
  print("Dictionary is empty")

This uses the in operator to check if a dummy value is present in the .values() view returned by the dictionary.

If any value exists, in will return True, indicating the dictionary has values and is not empty.

Another approach is to use len() on the dict.values() view object:

my_dict = {}

if len(my_dict.values()) == 0:
  print("Dictionary is empty")
else:
  print("Dictionary contains values")

By checking the length of the values view, we can count the actual values present. If the length is 0, there are no values.

I generally recommend the in operator approach for simplicity and better performance. The values() method is slower for large dictionaries since it scans all values.

In summary, we can use the presence of values as another technique to test for dictionary emptiness in Python.

Check Keys and Values Together for Full Emptiness

One tricky case is when a dictionary contains keys but no values, or values but no keys.

In these cases, the dictionary is not fully empty, so we may want to check if both the keys AND values are empty to guarantee full emptiness.

Here’s an example dictionary with just keys but no values:

my_dict = {"key1": "", "key2": ""}

To check if both the keys and values are empty:

if len(my_dict.keys()) == 0 and len(my_dict.values()) == 0:
  print("Dictionary is fully empty")

This checks the lengths of both the keys and values views. If both are 0, we can confirm the dictionary is completely empty.

Checking both keys and values lengths gives us a precise test for full emptiness when needed.

This covers the main techniques for checking dictionary emptiness and presence in Python. Let’s do a quick recap of what we learned:

  • Use length property for a simple emptiness check
  • Convert to bool if you want an explicit True/False
  • Check for presence of keys or values using in operator
  • Get lengths of keys and values for full emptiness test

Using the length property or in operator will cover most cases concisely and efficiently.

Leave a Reply

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