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.
Python Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# 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:
1 2 3 4 |
The original list is : [10, {'gfg': 1}, {'ide': 2, 'code': 3}, 20] The Dictionary count : 2 |
Source:
https://www.geeksforgeeks.org/count-dictionaries-in-a-list-in-python/