Count Number of Dictionaries in List in Python (3 Examples)

 

In this article, we will show how to count the number of dictionaries in a list in the Python programming language.

The content is structured as follows:

Let’s dive right into the examples!

 

Creation of Example Data

The first step in this tutorial is to create an example list:

my_list = ['january', {'february': 2},
          {'march': 5}, 'april',
          'may', {'june': 1},
          'july', ' august',
          {'september': 2}, 'october',
          'november', {'december': 4}]
 
print(my_list)
# ['january', {'february': 2},
# {'march': 5}, 'april',
# 'may', {'june': 1},
# 'july', ' august',
# {'september': 2}, 'october',
# 'november', {'december': 4}]

Have a look at the previous output. We have constructed a list object containing 7 strings (e.g., “january”) and 5 dictionaries (e.g., {“february”: 2}). Let’s see how to count the dictionaries in my_list!

 

Example 1: Count Number of Dictionaries in List Calling isinstance() Function inside List Comprehension

In this example, I will show how to use the isinstance() function within the list comprehension method to count the number of dictionaries in a list:

len([d for d in my_list if isinstance(d, dict)])
# 5

As you can see, the printed number of dictionaries is 5 as expected.

 

Example 2: Count Number of Dictionaries in List Calling isinstance() and sum() Functions

This example represents an alternative to count the number of dictionaries in a list. This time we will combine the isinstance() function with the sum() function using the Python script below.

sum(1 for d in my_list if isinstance(d, dict))
# 5

As shown, the sum() function adds 1s up to the total number of dictionaries while iterating through my_list. Not a coincidence that the total count of dictionaries is also 5 in this example 🙂

 

Example 3: Define Function to Count Number of Dictionaries in List

Different from the first two examples, we will create our own function to count the number of dictionaries in our list. Consider the code creating the user-defined function CountDict() below. It iterates through the elements in a list to get the total number of dictionaries by using the isinstance() function.

def CountDict(example_list):
    dictionaries = 0
    if isinstance(example_list, str):
        return 0
    if isinstance(example_list, dict):
        return CountDict(example_list.values()) + CountDict(example_list.keys()) + 1
    try:
        for i in example_list:
            dictionaries = dictionaries + CountDict(i)
    except TypeError:
        return 0
    return dictionaries

Now, we can apply this function to our list and print the output as follows.

print(CountDict(my_list))
# 5

As shown, CountDict() counts 5 dictionaries as supposed to.

 

Video, Further Resources & Summary

Do you need more explanations on how to count the number of dictionaries in a list? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

 

The YouTube video will be added soon.

 

You might be interested in other tutorials on Statistics Globe:

This post has shown different ways to count the number of dictionaries in a list in Python. Please let us know in the comments section below if you have additional questions.

 

Paula Villasante Soriano Statistician & R Programmer

This page was created in collaboration with Paula Villasante Soriano. Please have a look at Paula’s author page to get more information about her academic background and the other articles she has written for Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top