Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Check if dictionary is empty
During analysis of data sets we may come across situations where we have to deal with empty dictionaries. In this article we will see how to check if a dictionary is empty or not.
Using if Statement
The if condition evaluates to True if the dictionary has elements. Otherwise it evaluates to False. This is the most Pythonic way to check dictionary emptiness ?
Example
dict1 = {1: "Mon", 2: "Tue", 3: "Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : ", (dict1))
print("The original dictionary : ", (dict2))
# Check if dictionary is empty
if dict1:
print("dict1 is not empty")
else:
print("dict1 is empty")
if dict2:
print("dict2 is not empty")
else:
print("dict2 is empty")
The output of the above code is ?
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
dict1 is not empty
dict2 is empty
Using bool() Function
The bool() method evaluates to True if the dictionary is not empty. Else it evaluates to False. This explicitly converts the dictionary to a boolean value ?
Example
dict1 = {1: "Mon", 2: "Tue", 3: "Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : ", (dict1))
print("The original dictionary : ", (dict2))
# Check if dictionary is empty
print("Is dict1 empty? :", not bool(dict1))
print("Is dict2 empty? :", not bool(dict2))
print("Is dict1 non-empty? :", bool(dict1))
print("Is dict2 non-empty? :", bool(dict2))
The output of the above code is ?
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
Is dict1 empty? : False
Is dict2 empty? : True
Is dict1 non-empty? : True
Is dict2 non-empty? : False
Using len() Function
Another approach is to check the length of the dictionary using len(). An empty dictionary has length 0 ?
Example
dict1 = {1: "Mon", 2: "Tue", 3: "Wed"}
dict2 = {}
# Check using len()
print("Length of dict1:", len(dict1))
print("Length of dict2:", len(dict2))
print("Is dict1 empty?", len(dict1) == 0)
print("Is dict2 empty?", len(dict2) == 0)
The output of the above code is ?
Length of dict1: 3 Length of dict2: 0 Is dict1 empty? False Is dict2 empty? True
Comparison
| Method | Syntax | Best For |
|---|---|---|
if dict |
if my_dict: |
Most Pythonic, readable |
bool() |
bool(my_dict) |
Explicit boolean conversion |
len() |
len(my_dict) == 0 |
When you need the actual count |
Conclusion
Use if dict for the most Pythonic approach to check dictionary emptiness. The bool() and len() methods provide alternative ways for explicit checks.
