Check if Dictionary is Empty

Python: Check if Dictionary is Empty

Dictionaries are Python’s implementation of an associative list, which is a data structure. A dictionary is a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Examples:

Input:

dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

Output:

Dictionary is not empty

Input:

dictionary= { }

Output:

Dictionary is empty

Given a dictionary, the task is check if dictionary is empty or not.

Check if Dictionary is Empty

There are 2 ways to check if the dictionary is empty they are:

Method #1: Using if operator

A dictionary can be cast or converted to a bool variable in Python. If the dictionary is empty, it will be True; otherwise, it will be False.

We can now apply this concept by directly inserting a dictionary object into the if statement. If we pass the dictionary object into the if statement, it will be implicitly converted to a bool value. If the dictionary is empty, it returns True otherwise, it returns False.

Below is the implementation:

Example-1:

# given dictionary
dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

# checking if dictionary  is empty
if dictionary:
    print("Dictionary is not empty")
else:
    print("Dictionary is empty")

Output:

Dictionary is not empty

Example-2:

# given dictionary
dictionary = {}

# checking if dictionary  is empty
if dictionary:
    print("Dictionary is not empty")
else:
    print("Dictionary is empty")

Output:

Dictionary is empty

Method #2:Using len() function

When we pass the dictionary object to the len() function, we get the number of key-value pairs in the dictionary. So, we can use the len() function to determine whether or not the dictionary is empty.

If the length of dictionary is 0 then dictionary is empty otherwise not.

Below is the implementation:

Example -1:

# given dictionary
dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

# checking if dictionary  is empty using len() function
if len(dictionary) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output:

Dictionary is not empty

Example-2:

# given dictionary
dictionary = {}

# checking if dictionary  is empty using len() function
if len(dictionary) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output:

Dictionary is empty

Related Programs: