Count how many times each category appears in a list of labels. The naive loop seeds each new key with 0 the first time it is seen, then increments it on every visit. The replay shows counts growing one key at a time.

By hand

The Pythonic way

Counter(labels) does the same counting in one call, returning a Counter subclass of dict. Sorting the keys before printing ensures a deterministic RESULT regardless of insertion order.

naive.py
labels = ['a', 'b', 'a', 'c', 'b', 'a', 'b', 'a']
counts = {}
for x in labels:
    if x not in counts:
        counts[x] = 0
    counts[x] = counts[x] + 1
print('RESULT:', {k: counts[k] for k in sorted(counts)})
library.py
from collections import Counter
labels = ['a', 'b', 'a', 'c', 'b', 'a', 'b', 'a']
counts = Counter(labels)
print('RESULT:', {k: counts[k] for k in sorted(counts)})
RESULT: {'a': 4, 'b': 3, 'c': 1}

Implementation notes

  • counts grows in insertion order (a first, then b, then c); the printed RESULT uses a comprehension over sorted(counts) to give alphabetical order regardless.
  • Counter also supports counts.most_common() for frequency-sorted output, and arithmetic between counters.
  • The if x not in counts: counts[x] = 0 idiom is equivalent to counts.setdefault(x, 0) or counts.get(x, 0) + 1.