Library contents

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

  1. Start with A, B, A
  2. Do this Count each key
  3. Result A has 2, B has 1
The second A increases the existing A count from one to two.

Syntax

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

First output linenew 2
lesson.py
from collections import Counter

counts = Counter(["new", "sent", "new"])
for status in ("new", "held"):
    print(status, counts[status])
print("held" in counts)
Output
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

Advertisements

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?

GivenN · S · N · N | count N
Worked result3

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?

Givenready · held · ready | count ready
Worked result2