Count dictionaries in a list in Python
Last Updated :
01 May, 2023
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
test_list = [ 10 , { 'gfg' : 1 }, { 'ide' : 2 , 'code' : 3 }, 20 ]
print ("The original list is : " + str (test_list))
res = len ([ele for ele in test_list if isinstance (ele, dict )])
print ("The Dictionary count : " + str (res))
|
Output:
The original list is : [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]
The Dictionary count : 2
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary Space: O(1), as the space used by the program is constant and does not depend on the input size. The program only creates a single list comprehension and a few variables to store the input list and the result.
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
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
test_list = [ 10 , { 'gfg' : 1 }, { 'code' : 3 , 'ide' : 2 }, 20 ]
print ("The original list is : " + str (test_list))
res = hlper_fnc(test_list)
print ("The Dictionary count : " + str (res))
|
Output:
The original list is : [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]
The Dictionary count : 2
Time Complexity: O(n*n) where n is the number of elements in the dictionary. The recursion + isinstance() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary.
Method 3: Using filter() and lambda function
Algorithm
- Initialize the list ‘test_list’ containing elements of different types.
- Print the original list.
- Define a lambda function that takes a variable ‘x’ and returns True if ‘x’ is a dictionary, else False.
- Apply the filter() function on ‘test_list’ using the lambda function, which returns a filter object containing only the dictionaries in the list.
- Convert the filter object to a list using the list() function.
- Find the length of the resulting list, which gives the count of dictionaries in the original list.
- Print the count of dictionaries.
Python3
test_list = [ 10 , { 'gfg' : 1 }, { 'ide' : 2 , 'code' : 3 }, 20 ]
print ( "The original list is : " + str (test_list))
res = len ( list ( filter ( lambda x: isinstance (x, dict ), test_list)))
print ( "The Dictionary count : " + str (res))
|
Output
The original list is : [10, {'gfg': 1}, {'ide': 2, 'code': 3}, 20]
The Dictionary count : 2
Time Complexity: O(n)
The filter() method runs through each element in the list once, making this a linear operation in terms of time complexity.
Space Complexity: O(n)
The filter() method returns a new list containing all the elements that satisfy the given condition, so the space complexity is proportional to the size of the input list. However, since we are converting the filter object into a list, the space complexity is still considered to be O(n).
Method #4: Using sum + list comprehension The combination of the above functionalities can be used to solve this problem. In this, we count 1 on occurrence of an element and sum total the values.
Python
test_list = [ 10 , { 'gfg' : 1 }, { 'ide' : 2 , 'code' : 3 }, 20 , { 'geek' : 'sam' }]
print ( "The original list is : " + str (test_list))
res = sum ( 1 for i in test_list if type (i) = = dict )
print ( "The Dictionary count : " + str (res))
|
Output
The original list is : [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20, {'geek': 'sam'}]
The Dictionary count : 3
Time Complexity: O(N) N is the length of the list.
Auxiliary Space: O(1) Because no extra space is used.
Similar Reads
Python - Find all elements count in list
In Python, counting the occurrences of all elements in a list is to determine how many times each unique element appears in the list. In this article, we will explore different methods to achieve this. The collections.Counter class is specifically designed for counting hashable objects. It provides
3 min read
Python | Common items among dictionaries
Sometimes, while working with Python, we can come across a problem in which we need to check for the equal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let's discuss certain ways in which this task can be performed. Method #1 : Us
6 min read
Difference between List and Dictionary in Python
Lists and Dictionaries in Python are inbuilt data structures that are used to store data. Lists are linear in nature whereas dictionaries stored the data in key-value pairs. In this article, we will see the difference between the two and find out the time complexities and space complexities which ar
6 min read
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game
3 min read
How to Create a Dictionary in Python
The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Count distinct elements in an array in Python
Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
2 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a ke
5 min read
Python - Access Dictionary items
A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets. Example: [GFGTABS] Python a = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value a
3 min read
Get length of dictionary in Python
Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Letâs explore the various methods. Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in
3 min read
Initializing dictionary with Empty Lists in Python
In Python, it's common to encounter scenarios where you need to store lists in a dictionary. Often, this involves checking if a key exists and then creating a list for that key. However, a more efficient approach is to initialize the dictionary keys with empty lists from the start. Let's explore som
5 min read