Python collections.Counter
Counter maps hashable items to counts. Looking up an absent item returns zero, which makes it convenient for fixed-category reports.
A simple example
collections.Counter
- Start with A, B, A
- Do this Count each key
- Result A has 2, B has 1
Syntax
counts = Counter(events)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Count events and include missing categories
An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.
from collections import Counter
counts = Counter(["new", "sent", "new"])
for status in ("new", "held"):
print(status, counts[status])
print("held" in counts)
new 2 held 0 False
Use the report's requested ordering when printing categories. A zero returned by lookup does not mean that key was stored in the counter.
Python documentation for collections.Counter
Count north-door returns
A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?
Count ready print jobs
A print desk groups the current jobs by status. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?