How to check if a dictionary is empty in python?

In Python, you can check if a dictionary is empty by using the built-in function len or comparing the dictionary to an empty dictionary {}. Here are two methods for checking if a dictionary is empty:

Method 1: Using the len function

Method 2: Comparing the dictionary to an empty dictionary {}

Both methods will produce the same output:

The dictionary is empty

The built-in bool function in Python can also be used to determine whether a dictionary is empty. The bool function returns True, if the argument passed to it is truthy (i.e., if the argument has a truth value of True) and False, if the argument passed to it is falsy (i.e., if the argument has a truth value of False).

For dictionaries, an empty dictionary is considered falsy, while a non-empty dictionary is considered truthy. It means that the following code can be used to check whether a dictionary is empty using the bool function.

Output:

The dictionary(d) is not empty

You can also use the not operator in Python to check if a dictionary is empty. The truth value of the operand is inverted by the not operator. For dictionaries, an empty dictionary is considered falsy, while a non-empty dictionary is considered truthy. It means that you can do the following to see if a dictionary is empty by using the not operator:

Output:

The dictionary(d) is not empty





Latest Courses