Skip to main content

How to Count Values for Each Key in a Dictionary in Python

When a Python dictionary contains values that are themselves collections (like lists, tuples, or sets), a common task is to count the number of items within each of these collections. For example, given a dictionary like {'fruits': ['apple', 'banana'], 'vegetables': ['carrot']}, you might want to find out that there are 2 fruits and 1 vegetable.

This guide will demonstrate the most Pythonic ways to achieve this, from a simple for loop for printing results to a dictionary comprehension for creating a new dictionary of counts. It will also cover how to handle cases where you need to exclude empty or invalid items from your count.

The Scenario: A Dictionary of Collections

Let's start with a sample dictionary where each key maps to a list of strings. Our goal is to count the number of strings in each list.

data = {
"key_1": ["a", "b", "c"],
"key_2": ["z", "x"],
"key_3": ["q", "w", "e", "r"]
}

Method 1: Using a for Loop and len()

The most straightforward approach is to iterate over the dictionary's items using the .items() method, which yields key-value pairs. In each iteration, you can use the built-in len() function to get the size of the value (the list).

Solution:

data = {
"key_1": ["a", "b", "c"],
"key_2": ["z", "x"],
"key_3": ["q", "w", "e", "r"]
}

for key, value in data.items():
# 'value' is the list, and len(value) gets its length.
item_count = len(value)
print(f"'{key}' has {item_count} items.")

Output:

'key_1' has 3 items.
'key_2' has 2 items.
'key_3' has 4 items.

This method is perfect for when you simply need to print or log the counts.

Method 2: Using a Dictionary Comprehension (Pythonic)

If you want to create a new dictionary that maps each key to its corresponding count, a dictionary comprehension is the most elegant and efficient solution.

Solution:

data = {
"key_1": ["a", "b", "c"],
"key_2": ["z", "x"],
"key_3": ["q", "w", "e", "r"]
}

# This comprehension iterates through 'data' and builds a new dictionary.
counts = {key: len(value) for key, value in data.items()}

print(counts)
print(f"Count for 'key_3': {counts['key_3']}")

Output:

{'key_1': 3, 'key_2': 2, 'key_3': 4}
Count for 'key_3': 4

Handling Conditional Counting (e.g., Filtering Empty Strings)

Sometimes, you may need to exclude certain items from the count, such as empty strings ("") or None values. A simple len() call will include these, so you need to filter them out first.

Example of the problem:

data_with_empty_values = {
"key_1": ["a", "b", "c", ""],
"key_2": ["z", "", "x", None],
"key_3": ["q", "w", ""]
}

# A simple len() gives an inaccurate count of valid items.
incorrect_counts = {key: len(value) for key, value in data_with_empty_values.items()}
print(f"Incorrect counts: {incorrect_counts}")

Output:

Incorrect counts: {'key_1': 4, 'key_2': 4, 'key_3': 3}

Solution: Filter Before Counting. You can filter out "falsy" values (like "", None, 0) by checking the boolean value of each item.

data_with_empty_values = {
"key_1": ["a", "b", "c", ""],
"key_2": ["z", "", "x", None],
"key_3": ["q", "w", ""]
}

# Create a new dictionary, counting only the "truthy" items in each list.
correct_counts = {
key: sum(1 for item in value if item)
for key, value in data_with_empty_values.items()
}

print(f"Correct counts: {correct_counts}")

Output:

Correct counts: {'key_1': 3, 'key_2': 2, 'key_3': 2}
note

The expression sum(1 for item in value if item) is a Pythonic way to count items in an iterable that satisfy a condition. It creates a generator that yields 1 for each "truthy" item, and sum() adds them up.

An alternative is len(list(filter(bool, value))), which achieves the same result.

Conclusion

Counting the number of values associated with keys in a dictionary is a simple task once you identify your goal.

If you want to...The best solution is...Example
Print or log the countsA for loop with .items() and len()for k, v in d.items(): print(len(v))
Create a new dictionary of countsA dictionary comprehension{k: len(v) for k, v in d.items()}
Exclude certain items from the countA conditional expression inside your loop or comprehension{k: sum(1 for i in v if i) for k, v in d.items()}

By choosing the right pattern, you can write code that is both efficient and easy to read.