Use Standard Library Collection Tools
Replace two familiar manual loops with Counter and defaultdict only after verifying that the shorter versions produce the same result.
The measurement program already knows how to count labels and group readings with ordinary dictionaries. Python's standard library contains tools that can express the same work more directly. We will compare each tool with the loop it replaces before relying on the shorter form.
Begin with the Manual Count
Suppose the accepted readings have already been classified:
classes = ["low", "high", "ordinary", "low", "high"]
The Chapter 6 counting loop remains valid:
It produces:
{'low': 2, 'high': 2, 'ordinary': 1}
This loop makes the state change visible. The first occurrence creates a key; later occurrences update the value stored under that key. The standard-library tool should reproduce this result, not change its meaning.
Q1. Trace the next count
After the first four labels have been processed, manual_counts is
{'low': 2, 'high': 1, 'ordinary': 1}. What changes when the final label
"high" arrives?
Select one choice, then check.
HintFind the matching key
The final input is "high", and that key already exists.
SolutionUpdate the existing count
The expression reads the current value 1, adds one, and stores 2 under
the same high key.
Count with Counter
Counter belongs to the standard-library module collections. It accepts an
iterable of values and counts how often each value occurs:
The result is:
2
[('low', 2), ('high', 2), ('ordinary', 1)]
counter_counts["low"] uses ordinary dictionary-style lookup. The
most_common() method returns (value, count) pairs from more common to less
common. When equal counts matter, do not invent a ranking from their displayed
order; state a separate tie rule if the program needs one.
We can verify that the imported tool and the visible loop agree:
assert dict(counter_counts) == manual_counts
The conversion to dict makes the comparison explicit. Counter is a
dictionary subclass, but its purpose is narrower: counting repeated values.
It is useful after the counting rule is already understood. Because
collections is part of Python's standard library, it does not need a separate
package installation.
Begin with the Manual Group
Counting stores one number per key. Grouping stores several values per key. Use repeated sensor readings so the difference remains visible:
The first reading for a sensor creates one empty list. Every reading then joins the list stored under that sensor's label. The outer dictionary owns the labels; the inner lists hold the readings.
Group with defaultdict
defaultdict can create the missing list for us:
The argument list is a factory: a callable that produces a new value.
When grouped[label] looks up a missing key, defaultdict calls list() and
stores the new empty list before returning it. A later lookup of the same key
returns the existing list.
This automatic creation is helpful only when a missing key really means “begin a new group.” If a missing key should reveal a spelling mistake or an incomplete record, an ordinary dictionary keeps that mistake visible.
Q2. Reproduce the manual results
Complete the two standard-library expressions. The assertions must confirm that the shorter forms produce the same count and grouping as the manual results.
Editable Python
Ready to run.
HintUse each tool for one role
Construct the counter from classes. Construct the grouping with
defaultdict(list), then append each reading under its label.
SolutionKeep counting and grouping separate
Read a Nested Count Without Hiding It
Later text-processing programs often count one category inside another. Once
both tools are familiar, defaultdict(Counter) is readable:
The output is 2. The outer defaultdict creates one Counter for a new
sensor. The inner Counter updates the status count. This compact form should
be read from the outside inward; it does not create a different kind of
counting rule.
Q3. Choose automatic creation deliberately
Which situation is the clearest use of defaultdict(list)?
Select one choice, then check.
HintAsk what a missing key means
Automatic creation is useful when absence means “start an empty group,” not when absence should expose a mistake.
SolutionCreate only legitimate groups automatically
The new-sensor case fits defaultdict(list). Required configuration should
keep missing keys visible, and one replaceable value needs only an ordinary
dictionary assignment.
Counter and defaultdict shorten two dictionary loops whose behavior we can
already explain and verify. They are useful because their names state the
collection's role, not because imported code makes counting or grouping a new
operation. The final lesson will place these reusable operations inside one
small program with clear file responsibilities.