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")
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: