w3resource

Python: Check a dictionary is empty or not

Python dictionary: Exercise-18 with Solution

Write a Python program to check if a dictionary is empty or not.

Sample Solution:

Python Code:

# Create an empty dictionary 'my_dict'.
my_dict = {}

# Check if the dictionary is empty by evaluating its boolean value.
# The 'bool()' function returns False for an empty dictionary, so if it's not empty, the condition is True.
if not bool(my_dict):
    # Print a message indicating that the dictionary is empty.
    print("Dictionary is empty")

Sample Output:

Dictionary is empty 

Python Code Editor:

Previous: Write a Python program to remove duplicates from Dictionary.
Next: Write a Python program to combine two dictionary adding values for common keys.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-18.php