Check if dictionary value is empty in Python

If you work with dictionaries, sometimes, you will have to check whether a dictionary is empty.

In programming, usually, there are many ways to get the same result. In this lesson, I’ll show you a few ways, you can achieve this goal.

The first way is the simplest, but the other three are also not very complicated. In our example, we are going to have three dictionaries: with a value, without a value, and with None.

Checking if directory value is empty

First example:

In order to use the first example, use the following code:

The my_dict dictionary has a value, and the empty_dict doesn’t have any, therefore adequate messages are returned.

Second example:

The second example has a bit longer notation. In this case, we are going to use the bool function. Just add bool after not.

The result is the same for all examples. This is a less pythonic way to get the same result.

Third example:

In the third example, we are not going to use bool. Instead, we will try a different function, called len. This function returns the number of elements inside an object. If len(dict) == 0, then the object is empty.

If the directory is not empty, then the code will return the number of directory elements. Apart from that, the code returns the same result as the one before.

Fourth way:

There is also a fourth way and this code returns a bit different result than before.

This code returns the following result:

Notice, that the last part of the code treats None value differently than the examples before. If the dictionary is None, instead of empty, it will return that the directory is not empty.