Python | Count number of items in a dictionary value that is a list
Last Updated :
27 Apr, 2023
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 key is a list. To check that the value is a list or not we use the isinstance() method which is inbuilt in Python. isinstance() method takes two parameters:
object - object to be checked
classinfo - class, type, or tuple of classes and types
It return a boolean whether the object is an instance of the given class or not. Let's discuss different methods to count number of items in a dictionary value that is a list. Method #1 Using in operator
Python3
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using the in operator
count = 0
for x in d:
if isinstance(d[x], list):
count += len(d[x])
print(count)
# Calling Main
if __name__ == '__main__':
main()
Time Complexity: O(n), where n is the number of key-value pairs in the dictionary d. This is because the code iterates through each key-value pair in the dictionary using the for loop and for each key-value pair, it checks if the value is a list using the isinstance() function. If the value is a list, it increments the count by the length of the list. Finally, it prints the count.
Auxiliary Space: O(n), because it only uses a fixed amount of memory to store the dictionary d, the count, and the temporary variables x. It does not use any data structures that grow in proportion to the size of the input.
Method #2: Using list comprehension
Python3
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using list comprehension
print(sum([len(d[x]) for x in d if isinstance(d[x], list)]))
if __name__ == '__main__':
main()
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Method #3: Using dict.items()
Python3
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = { 'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using dict.items()
count = 0
for key, value in d.items():
if isinstance(value, list):
count += len(value)
print(count)
if __name__ == '__main__':
main()
Method #4: Using enumerate()
Python3
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using enumerate()
count = 0
for x in enumerate(d.items()):
# enumerate function returns a tuple in the form
# (index, (key, value)) it is a nested tuple
# for accessing the value we do indexing x[1][1]
if isinstance(x[1][1], list):
count += len(x[1][1])
print(count)
if __name__ == '__main__':
main()
Method#5: Using values(),find() and type().
Python3
# Python program to count number of items
# in a dictionary value that is a list.
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# values() - to fetch values of dictionary
count = 0
for x in list(d.values()):
# type() - returns type of a variable
type1=str(type(x))
# find() - returns position of a specified value if found else returns -1
if(type1.find('list')!=-1):
count+=len(x)
print(count)
if __name__ == '__main__':
main()
Method #6: Using Recursive method.
This function takes a dictionary d as its input, and recursively searches through all the values in the dictionary. If a value is a list, it adds the length of the list to the count. If a value is another dictionary, it calls the count_list_items function recursively on that dictionary and adds the result to the count.
Python3
def count_list_items(d):
count = 0
for v in d.values():
if isinstance(v, list):
count += len(v)
elif isinstance(v, dict):
count += count_list_items(v)
return count
def main():
# defining the dictionary
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
count=count_list_items(d)
print(count)
if __name__ == '__main__':
main()
The time complexity of this function is O(N), where N is the total number of elements in all the lists in the dictionary. This is because the function needs to examine each element in each list exactly once.
The space complexity of this function is also O(N), where N is the total number of elements in all the lists in the dictionary. This is because the function needs to keep track of the count, as well as the call stack for each level of recursion.
Similar Reads
Convert a list of Tuples into Dictionary - Python
Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value p
3 min read
Python - Number of values greater than K in list
In Python, Filtering data based on specific conditions is usually necessary. Counting the number of values greater than a given threshold K is a common task in data analysis, sorting, and threshold-based filtering in various applications. Python provides multiple methods to perform this efficiently.
2 min read
Count the Number of Null Elements in a List in Python
In data analysis and data processing, It's important to know about Counting the Number of Null Elements. In this article, we'll explore how to count null elements in a list in Python, along with three simple examples to illustrate the concept. Count the Number of Null Elements in a List in PythonIn
3 min read
How to count the number of lines in a CSV file in Python?
Counting the number of lines in a CSV file in Python means determining how many rows the file contains, including or excluding the header depending on your needs. For example, if your CSV file has 100 data rows plus one header row, the total line count is 101. We will use the following dataset to de
2 min read
Count number of lines in a text file in Python
Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output:
3 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained
3 min read
Count dictionaries in a list in Python
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
5 min read
Use get() method to Create a Dictionary in Python from a List of Elements
We are given a list of elements and our task is to create a dictionary where each element serves as a key. If a key appears multiple times then we need to count its occurrences. get() method in Python helps achieve this efficiently by providing a default value when accessing dictionary keys. For exa
1 min read
Python - Frequencies of Values in a Dictionary
Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let's discuss certain ways in which t
4 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets
4 min read