How to Count the Number of Dictionaries in an Array in Python?

Estimated read time 2 min read

To count the number of dictionaries in a Python array, you can use a loop to iterate over each element in the array and check if it is a dictionary using the isinstance() function.

Here’s an example:

# create a sample array
my_array = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35}, 'not a dictionary']

# initialize a counter variable
count = 0

# iterate over each element in the array
for element in my_array:
    if isinstance(element, dict):
        count += 1

print(f'The array contains {count} dictionaries.')

In this example, we create a sample array containing three dictionaries and one non-dictionary element. We then initialize a counter variable to zero and use a loop to iterate over each element in the array. For each element, we check if it is a dictionary using the isinstance() function. If it is, we increment the counter variable by one.

Finally, we print a message to the console indicating the number of dictionaries in the original array. The output will be:

The array contains 3 dictionaries.

Note that this approach only works for arrays (lists) containing dictionaries. If your array contains a mix of dictionary and non-dictionary elements of different types, you will need to modify the loop accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply