w3resource

Python: Count number of items in a dictionary value that is a list


34. Count Number of Items in Dictionary Value That is a List

Write a Python program to count the number of items in a dictionary value that is a list.

Visual Presentation:

Python Dictionary: Count number of items in a dictionary value that is a list.

Sample Solution:

Python Code:

# Create a dictionary 'dict' with names as keys and lists of subjects as values.
dict =  {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']}

# Calculate the total number of subjects by summing the lengths of the lists (values) in the dictionary.
ctr = sum(map(len, dict.values()))

# Print the total count of subjects.
print(ctr) 

Sample Output:

5

For more Practice: Solve these Related Problems:

  • Write a Python program to iterate over a dictionary and for each key whose value is a list, print the count of items in that list.
  • Write a Python program to use dictionary comprehension to create a new dictionary mapping each key to the length of its list value.
  • Write a Python program to sum the number of items across all list values in a dictionary.
  • Write a Python program to implement a function that returns the total count of elements in all list-type values in a dictionary.

Python Code Editor:

Previous: Write a Python program to check multiple keys exists in a dictionary.
Next: Write a Python program to sort Counter by value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.