Skip to content
Related Articles
Open in App
Not now

Related Articles

Count dictionaries in a list in Python

Improve Article
Save Article
  • Last Updated : 29 Apr, 2020
Improve Article
Save Article

A list in Python may have items of different types. Sometimes, while working with data, we can have a problem in which we need to find the count of dictionaries in particular list. This can have application in data domains including web development and Machine Learning. Lets discuss certain ways in which this task can be performed.

Input : test_list = [4, 5, ‘gfg’]
Output : 0

Input : test_list = [{‘gfg’ : 1}]
Output : 1

Input : test_list = [10, {‘gfg’ : 1}, {‘ide’ : 2, ‘code’ : 3}, 20]
Output : 2

Input : test_list = [4, 5, ‘gfg’, {‘best’: 32, ‘gfg’: 1}, {‘CS’: 4}, (1, 2)]
Output : 2

Method #1 : Using list comprehension + isinstance()
The combination of above functionalities can be used to solve this problem. In this, we perform iteration using list comprehension and test for dictionary using isinstance().




# Python3 code to demonstrate working of 
# Dictionary Count in List
# Using list comprehension + isinstance()
  
# initializing list
test_list = [10, {'gfg' : 1}, {'ide' : 2, 'code' : 3}, 20]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Dictionary Count in List
# Using list comprehension + isinstance()
res = len([ele for ele in test_list if isinstance(ele, dict)])
  
# printing result 
print("The Dictionary count : " + str(res)) 

Output:

The original list is : [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]
The Dictionary count : 2

 

Method #2 : Using recursion + isinstance() ( for nested dictionaries)
The combination of above functionalities can be used to solve this problem. In this, we also solve the problem of inner nesting using recursion.




# Python3 code to demonstrate working of 
# Dictionary Count in List
# Using recursion + isinstance()
  
# helper_func
def hlper_fnc(test_list):
    count = 0
    if isinstance(test_list, str):
        return 0
    if isinstance(test_list, dict):
        return hlper_fnc(test_list.values()) + hlper_fnc(test_list.keys()) + 1
    try:
        for idx in test_list:
            count = count + hlper_fnc(idx)
    except TypeError:
        return 0
    return count
  
# initializing list
test_list = [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Dictionary Count in List
# Using recursion + isinstance()
res = hlper_fnc(test_list)
  
# printing result 
print("The Dictionary count : " + str(res)) 

Output:

The original list is : [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]
The Dictionary count : 2

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!