5 Ways to Verify if a Dictionary is Empty in Python

5 Ways to Verify if a Dictionary is Empty in Python

You can check if a dictionary is empty by using various methods in Python. Here are five examples:

  1. Using len() function:
my_dict = {}
if len(my_dict) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")
  1. Directly checking against boolean value:
my_dict = {}
if not my_dict:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")
  1. Using bool() function:
my_dict = {}
if bool(my_dict) == False:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")
  1. Checking for truthiness of dictionary items:
my_dict = {}
if all(value is None for value in my_dict.values()):
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")
  1. Using not with dictionary comprehension:
my_dict = {}
if not any(my_dict):
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

All these examples will correctly determine whether the dictionary my_dict is empty or not.