Python Practice › Collections Programs › Program 6
Count with defaultdict(int)
Write a Python program to count characters with defaultdict(int).
Output
{'b': 1, 'a': 3, 'n': 2}Approach
- Missing keys start at 0.
Solution
from collections import defaultdict counts = defaultdict(int)for ch in "banana": counts[ch] += 1print(dict(counts))Output
{'b': 1, 'a': 3, 'n': 2}Learn the concept
New to this topic? Read the lesson, then come back.