How can I determine if a dictionary is empty?

Question

Is it possible to determine whether a dictionary is empty?

Answer

Yes, there are several ways to check if a dictionary is empty. The more standard Python method is to use a Boolean evaluation on the dictionary. An empty dictionary (or other containers) will evaluate to a Boolean False. You can do that by testing just the dictionary variable or using the bool() function. Both methods are shown in the following code example.

dict1 = {}

if dict1:
    print("dict1 Not Empty")
else:
    print("dict1 is Empty")

if bool(dict1):
    print("dict1 Not Empty")
else:
    print("dict1 is Empty")

Also, it is possible to use the len() function to test whether the dictionary is empty. If it is empty, the function will return 0. This method is shown in the code example below.

dict1 = {}

if len(dict1) == 0:
    print("dict1 is Empty")
10 Likes

Hello,
why not just print out the dictionary and see if it’s empty?
cheers

2 Likes

Sometimes you program might need to do different operations, based on whether or not the dictionary is empty.

print() will work for us, but not in conditionals for programming

9 Likes

Why not simply use:

my_dictionary=={}

That is also possibility. But empty dictionaries are false, so then you can also just use:

if dict1:
    print("dict1 Not Empty")
else:
    print("dict1 is Empty")
4 Likes

A good bit of information

Does same goes with List, String, Tuple and set?
for example:

a = []
if a:
  print("List is empty")
else:
  print("Not empty")
2 Likes

Yes, the technique described earlier in this thread to check if a dictionary is empty does work with lists.

The code you provided in your post will not work, however. It just needs to be changed slightly since the empty list evaluates to False and would run the else code block:

a = []
if a:
  print("List is not empty")
else:
  print("List is empty")

I encourage you to get in the habit of testing things like this on your local system by installing Python. This will really solidify your understanding and help you to cross over into personal development and application. Codecademy has some great videos to help you get Python installed and setup.

If that is not an option, you can easily test out your Python code online using a site like Repl.it. Here is a link for the online Python3 live code editor:

https://repl.it/languages/python3

Great question by the way!

3 Likes

Please give an example in the case of conditionals. : )

these examples are literally in the FAQ?

1 Like