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.
Share your thoughts in the comments
Please Login to comment...