Filtering and reducing the raw data with a Counter object

We'll represent the essential defect counts as a collections.Counter parameter. We will build counts of defects by shift and defect type from the detailed raw data. Here's the code that reads some raw data from a .csv file:

from typing import TextIOimport csvfrom collections import Counterfrom types import SimpleNamespacedef defect_reduce(input_file: TextIO) -> Counter:    rdr = csv.DictReader(input_file)    assert set(rdr.fieldnames) == set(        ["defect_type", "serial_number", "shift"])    rows_ns = (SimpleNamespace(**row) for row in rdr)    defects = (        (row.shift, row.defect_type)        for row in rows_ns if row.defect_type)    tally = Counter(defects)    return tally

The preceding function will create a dictionary ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.