Count with defaultdict(int)

EasyCollections Programs · 6 of 20

Write a Python program to count characters with defaultdict(int).

Advertisement
Output
{'b': 1, 'a': 3, 'n': 2}

Approach

  1. Missing keys start at 0.

Solution

Python
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.

More collections programs

← All 20 Collections Programs

Leave a Comment