check if dict is empty in python

7 Ways to Check if Dict is Empty in Python

Dictionary is one of the widely used Data structures in Python that stores an unordered collection of key-value pairs. In this article, we will discuss Dict in deep and different ways to create an empty dict and check if dict is empty in Python.

More about Dictionaries in Python

Dictionaries in Python are inbuild data structures that store the data in the format of key-value pairs. Dictionaries don’t allow ordered storage of data. However, you can still find out whether the key is present or not in constant time using hashing concept.

Here are the basic properties of Dictionaries:

  • Stores data in key-value pairs
  • Keys in a dictionary have to be unique whereas values can be duplicated.
  • Dictionaries cannot have null keys.
  • We can access the value based on the key in a constant time. Also, we can check if the key exists or not in constant time.

How to create an Empty Dictionary in Python?

An Empty dictionary is a dictionary that has no key-value pairs. You can follow any of these mentioned ways to create an empty dictionary in Python.

1. Using dict() function

To create an empty dictionary in Python, you can use dict() function without any arguments. Here is the code thread of this –

#create an empty dictionary with dict() function
empty_dict = dict()

print(empty_dict) # {}
type(empty_dict) # <class 'dict'>

2. With curly braces

Alternatively, you can also use curly braces to create and initiate a new dictionary.

#create empty dictionary using curly braces

empty_dict = {}

How to Check if Dict is Empty in Python?

We use Dictionaries in our regular day-to-day programming activities. Dictionary is a very efficient data structure when it comes to a few operations like checking whether the element is present or not and accessing the value based on the key.

A lot of business use cases require us to check if the dict is empty or not in Python. There might be a requirement to add the data to a dict if it is empty. So, in the below sections, we will be talking about different ways to check if the given dict is empty in Python.

Best Ways to Check if Dict is Empty in Python

Out of the 7 listed methods in Python to check if the dict is empty, using –

1. len() function and

2. boolean evaluation

These are the two most commonly used ways. Both these methods are straightforward and produce the required results in constant time.

1. Use len() function

len() function is the first thing that comes to our mind when we wanted to check the length of any collection. We can use it to check the length of the dictionary and eventually find out whether it is empty or not.

The len() function on dict returns ‘0′ if there are no elements in the dictionary. Here is the code for this –

#creating empty dictionary
empty_dict = {}

#using the len() function to check the dict size
if len(empty_dict) == 0:
    print("The given dictionary empty")
else:
    print("The given dictionary is not empty")

#output: The given dict is empty

2. With bool evaluation

Another simple way to check if the dict in Python is empty or not is by using boolean evaluation. An empty dictionary evaluates to False whereas the non-empty dict returns True. Let’s find out how we can check this condition.

Here in this example, we are going to use the not operator to check whether there are any elements present in dict or not.

#creating empty dict
empty_dict = {}

if not empty_dict:
    print("The given dict is empty")
else:
    print("The given dict is non-empty")


#output: The given dict is empty

3. bool() function

This method is also quite similar to that of the above one and uses the same concept as an empty dictionary in Python is treated as False in a Boolean context. Using bool() function, we can check if the dict is empty in Python.

# creating an empty dictionary
empty_dict = {}

if not bool(empty_dict):
    print('Dictionary is Empty')
else:
    print('Dictionary is not empty')


#output: Dictionary is Empty

4. By comparing it with Empty dict

We can compare the dictionary with curly braces (which denote empty dict) to check if the given dictionary is empty or not. It returns True if they both are the same and False otherwise.

# creating an empty dict
sample_dict = {}

if sample_dict == {}:
    print('Given dictionary is empty')
else:
    print('Given dictionary is not empty')

#output: Given dictionary is empty

5. Using any() function:

The any() function in Python returns True if atleast one of the element of an iterable is True, and False otherwise. We can use this condition to check if dict is empty in Python.

any() function takes iterable as an argument and returns Boolean value. If there are any elements exists in the dict, it returns True.

#creating an empty dict
empty_dict = {}

if not any(empty_dict):
    print('Given dictionary is empty')
else:
    print('Given dictionary is not empty')

#output: Given dictionary is empty

6. Use all() function

We are going to use all() function along with dict.values() to check if dict is empty in Python or not. The all() function returns True if all the elements are True. Since the empty dictionary has no values, all() function will return True.

Here is the code snippet for this –

#creating an empty dictionary
empty_dict = {}

if all(empty_dict.values()):
    print('Given dictionary is Empty')
else:
    print('Given dictionary is non-empty')

#output: Given dictionary is Empty

7. Check the emptiness of Dict using dict.items()

Here comes the final method in our guide to check python empty dict. The items() function on dict returns the dict_items class which returns True if it is non-empty.

# creating an empty dict
empty_dict = {}

if not empty_dict.items():
    print('Dictionary is Empty')
else:
    print('Dictionary is not empty')

#output: Dictionary is Empty

More about Dictionaries in Python

Dictionaries in Python are inbuild data structures that store the data in the format of key-value pairs. Dictionaries don’t allow ordered storage of data. However, you can still find out whether the key is present or not in constant time using hashing concept.

Here are the basic properties of Dictionaries:

  • Stores data in key-value pairs
  • Keys in a dictionary have to be unique whereas values can be duplicated.
  • Dictionaries cannot have null keys.
  • We can access the value based on the key in a constant time. Also, we can check if the key exists or not in constant time.

Now let’s see how can we perform some basic operations on dicts in Python. We are taking a dictionary that stores movie names and their corresponding box office collections in a dictionary.

To create empty dict in Python:

# To create empty dict in Python

movie_box_office = {}

To add elements to dict in Python:

# Code to add elements to a dict in Python

movie_box_office = {}

movie_box_office['Avatar'] = '$2,922,917,914'
movie_box_office['Avengers: Endgame'] = '$2,797,501,328'
movie_box_office['Titanic'] = '$2,201,647,264'

print(movie_box_office) # {'Avatar': '$2,922,917,914', 'Avengers: Endgame': '$2,797,501,328', 'Titanic': '$2,201,647,264'}

To update the value for a key:

# to update the box office information of movie Avengers: Endgame

movie_box_office['Avengers: Endgame'] = '$2,890,460,761'

print(movie_box_office) #{'Avatar': '$2,922,917,914', 'Avengers: Endgame': '$2,890,460,761', 'Titanic': '$2,201,647,264'}

To delete a key in dict:

del movie_box_office['Avatar']

To check if the key exists or not in a dict:

if 'Titanic' in movie_box_office:
    print('Titanic is present in Dictionary')

#output: Titanic is present in Dictionary

To get the value based on Key:

# Can use any of the below ways to get the value

movie_box_office['Titanic']

movie_box_office.get('Titanic')

#output: '$2,201,647,264'

To loop through the dictionary:

for movie_name, box_office in movie_box_office.items():
    print(movie_name, box_office)

Frequently Asked Questions

  • How to create an empty dict in Python?

    To create an empty dictionary, you can either use dict() function or curly braces. Detailed code with examples listed here.

  • How to check if the dict is Empty in Python?

    Check if the dictionary is empty or not in Python using different ways listed in this article. Using len() function and boolean evaluation are the two most used ways.

  • Is empty dict return None?

    Yes, an empty dict is treated as None and when you compare it with None, it returns True. Here is the code for this.

Read more about Python dictionaries from here

Follow codethreads.dev for more insightful stories like these. Please share this with your friends on Social media.

Leave a Comment

Your email address will not be published. Required fields are marked *