×

How to check if the dictionary is empty in Python?

What is a dictionary in Python?

A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its element, it holds elements in the format of key-value pair, where keys and values are separated by ‘:’ and two keys are separated by a comma. A dictionary can have identical values but it cannot store identical keys.

While creating a dictionary we should keep in mind that keys are case sensitive i.e., both ‘day’ and ‘Day’ will be considered as different keys as the first letter of both words is in a different case (small letter and capital letter).

Example 1:

# Creating an empty Dictionary  
dic1={} 
print("Example of an empty dictionary: \n ") 
print(dic1,"\n”) 
    
# Creating a Dictionary with different keys
dic1={'name': 'Amit', 1: [8, 1, 20, 4]} 
print("A normal dictionary using different Keys: \n ") 
print(dic1) 

Output:

Example of an empty dictionary: 
 {} 
A normal dictionary using different Keys: 
{'name': 'Amit', 1: [8, 1, 20, 4]}

Using the bool() function to check if a dictionary is empty

To perform this task, we use the bool function. This function converts the passed object to a Boolean value, but it is only possible if and only if the string is not empty. If an empty string is passed to this function, it returns false, as an empty string cannot be converted.

Example 2:

# Initializing empty dictionary
dict1={}
 
# Printing original dictionary with all its contents
print("The original dictionary : \n "+str(dict))
 
# Using thebool() function
# to checkthe status of the dictionary
rslt=notbool(dict1)
 
# Returning status of the dictionary
print("\nStatus of dictionary : \n "+str(rslt))


nw_dict={‘Name’: 'Amit', ‘Place’: 'Goa', ‘Object’: 'Pen', ‘Year’: '2022'}


print("\nThe original dictionary : \n "+str(nw_dict))
 
# Using thebool() function
# to check the status of the dictionary
rslt=notbool(nw_dict)
 
# Returning status of the dictionary
print("\nStatus of dictionary : \n "+str(rslt))

Output:

How to check if the dictionary is empty in Python

Using the not operator to check the status of the dictionary

Not operator can also be used to check the status of the dictionary, after using this operator it returns true if the dictionary is found out to be empty.

Example 3:

# Initializing empty dictionary
dict1={}
 
# Printing original dictionary with all its contents
print("The original dictionary : \n"+str(dict1))
 
# Using the not operator
# to check the status of the dictionary
rslt=notdict1
 
# Returning status of the dictionary
print("\nIs dictionary empty ? : \n "+str(rslt))


nw_dict={‘Name’: 'Amit', ‘Place’: 'Goa', ‘Object’: 'Pen', ‘Year’: '2022'}


# Printing original dictionary with all its contents
print("\nThe original dictionary : \n "+str(nw_dict))
 
# Using the not operator
# to check the status of the dictionary
rslt=notnw_dict
 
# Returning status of the dictionary
print("\nIs dictionary empty ? : "+str(rslt))

Output:

How to check if the dictionary is empty in Python

Using the len() function to check the status of the dictionary:

The len() function is also used to check the status of the dictionary when the dictionary is passed to this function, it returns its length and compares it and hence returns the result as true or false.

Example 4:

# Initializing empty dictionary
dict1={}
 
# Printing original dictionary with all its contents
print("The original dictionary : \n "+str(dict1))
 
# Using the len() function
# to checkthe status of the dictionary
rslt=len(dict1) ==0 


# Returning status of the dictionary
print("\nIs dictionary empty ? : \n "+str(rslt))


nw_dict={‘Name’: 'Amit', ‘Place’: 'Goa', ‘Object’: 'Pen', ‘Year’: '2022'}


# Printing original dictionary with all its contents
print("\nThe original dictionary : \n "+str(nw_dict))
 
# Using the len() function
# to check the status of the dictionary
rslt=len(nw_dict) ==0 


# Returning status of the dictionary
print("\nIs dictionary empty ? : \n "+str(rslt))

Output:

How to check if the dictionary is empty in Python

Using the Equality operator to check the status of the dictionary

 While using this method, we take an additional empty dictionary to compare it with the original one. And after comparing it, the result is returned as “True” or “False”.

Example 5:

# Initializing a dictionary check it against an empty dictionary
nw_dict={‘Name’: 'Amit', ‘Place’: 'Goa', ‘Object’: 'Pen', ‘Year’: '2022'}
# Initializing empty dictionary
tst_dict={}
 
# Printing original dictionary with all its contents
print("The original dictionary :\n  "+str(nw_dict))
 
# Using equality operator
# to check the status of the dictionary
rslt=tst_dict==nw_dict
 
# Returning status of the dictionary
print("\nIs dictionary empty ? : "+str(rslt))

Output:

The original dictionary :
‘Name’: 'Amit', ‘Place’: 'Goa', ‘Object’: 'Pen', ‘Year’: '2022'


Is dictionary empty ? : False

Related Topics

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python ascii() Function

Python ascii() Function The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc). This function will replace any non-ascii characters with escape characters. Syntax ascii(object) Parameter object:  An object, like String, List, Tuple, Dictionary, etc. Return This...

1 minute read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Python logging Module

Python logging Module Introduction By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging...

12 minutes read.

How to create a list in Python?

How to create a list in python Python is known for its versatility and its data structures help us to perform different kinds of operations on various datasets irrespective of their...

4 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.

Python vs R

Python: - Python is a popular high-level, general-purpose programming language. Python (the most recent version is Python 3) is a programming language used in the software industry for website development, machine...

3 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.