- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 tis article we will see how to check if a dictionary is empty or not.
Using if
The if condition evaluates to true if the dictionary has elements. Otherwise it evaluates to false. So in the below program we will just check the emptiness of a dictionary using only the if condition.
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")
Output
Running the above code gives us the following result −
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'} The original dictionary : {} dict1 is not empty dict2 is empty
Using bool()
The bool method evaluates to true if the dictionary is not empty. Else it evaluates to false. So we use this in expressions to print the result for emptiness of a dictionary.
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? :",bool(dict1)) print("Is dict2 empty? :",bool(dict2))
Output
Running the above code gives us the following result −
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'} The original dictionary : {} Is dict1 empty? : True Is dict2 empty? : False
Advertisements