# 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

 `# 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```

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

 `# 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```

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

1. Initialize the list ‘test_list’ containing elements of different types.
2. Print the original list.
3. Define a lambda function that takes a variable ‘x’ and returns True if ‘x’ is a dictionary, else False.
4. Apply the filter() function on ‘test_list’ using the lambda function, which returns a filter object containing only the dictionaries in the list.
5. Convert the filter object to a list using the list() function.
6. Find the length of the resulting list, which gives the count of dictionaries in the original list.
7. Print the count of dictionaries.

## Python3

 `# 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 filter() and lambda function` `res ``=` `len``(``list``(``filter``(``lambda` `x: ``isinstance``(x, ``dict``), test_list)))`   `# printing result ` `print``(``"The Dictionary count : "` `+` `str``(res))` `#This code is contributed by Vinay Pinjala.`

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

 `# initializing list` `test_list ``=` `[``10``, {``'gfg'` `: ``1``}, {``'ide'` `: ``2``, ``'code'` `: ``3``}, ``20``, {``'geek'` `: ``'sam'``}]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Dictionary Count in List` `# Using sum method` `res ``=` `sum``(``1` `for` `i ``in` `test_list ``if` `type``(i) ``=``=` `dict``)`   `# printing result` `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