Last modified: Aug 21, 2023 By Alexander Williams

Checking if a Nested Dictionary is Empty in Python

A nested dictionary in Python is a dictionary that has other dictionaries inside it. Here's an example of a nested dictionary:

nested_dict = {
    'a': {
        'x': 1,
        'y': 2
    },
    'b': {
        'z': 3
    }
}

However, you can use the following ways to see if a nested dictionary is empty:

Using Recursion

Recursion is a function that calls itself to solve smaller instances of the same problem in recursion. Here's how to use recursion to check if a nested dictionary is empty:

def is_nested_dict_empty(nested_dict):
    if not isinstance(nested_dict, dict):
        raise ValueError("Input must be a dictionary")

    if not nested_dict:
        return True

    for value in nested_dict.values():
        if isinstance(value, dict):
            if not is_nested_dict_empty(value):
                return False
        elif value:
            return False

    return True

In this function:

  1. Check if the input is a dictionary.
  2. If the input is a dictionary, check if the dictionary is empty.
    • If the dictionary is empty, return True.
    • If the dictionary is not empty, iterate through its values.
  3. For each value in the dictionary:
    • If the value is a dictionary, recursively call the is_nested_dict_empty() function on that value.
    • If the value is not a dictionary, check if the value is empty.
      • If the value is not empty, return False.
  4. If no non-empty values are found, return True.

Now let's see how to use this function.

# nested dictionary
nested_dict = {
    "key1": {
        
    },
    "key3": {
    },
}
    
    
is_nested_dict_empty(nested_dict)

Output:

True

Using all() Function

You can also use the all() function and a generator expression to check if a nested dictionary is empty. This method is shorter and more Pythonic:

def is_nested_dict_empty(nested_dict):
    if not isinstance(nested_dict, dict):
        raise ValueError("Input must be a dictionary")

    return all(is_nested_dict_empty(value) if isinstance(value, dict) else not value for value in nested_dict.values())

In this function, The all() function takes an iterable object as input and returns True if all of the elements in the iterable object are True.

Conclusion

In this article, we've looked at two ways to use Python to see if a nested dictionary is empty.

The first way uses recursion to go through the structure's levels and check if each is empty.

The all() function and a generator expression are used in the second way to get the same result more quickly.