Grouping
Group Count
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
countsgrows in insertion order (afirst, thenb, thenc); the printed RESULT uses a comprehension oversorted(counts)to give alphabetical order regardless.Counteralso supportscounts.most_common()for frequency-sorted output, and arithmetic between counters.- The
if x not in counts: counts[x] = 0idiom is equivalent tocounts.setdefault(x, 0)orcounts.get(x, 0) + 1.