Using a Dictionary to Group Records

A grouping map stores one collection for each key and preserves every received record in the appropriate group.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Build the rows by label
  2. Choose the intended information
  3. Build independently owned buckets
  4. Pick the lightest summary that still supports the query

Build the rows by label

Given sales (north, 2), (west, 4), and (north, 5), create north's list with 2, west's with 4, then append 5 to north. The two northern observations remain available. This follows grouping values by a computed key.

Choose the intended information

A map of sums would store north as seven and lose the individual amounts. That may suffice for totals. A report that also needs a median should preserve values or another appropriate summary. Loop accumulators clarify which state serves each output.[1]

Build independently owned buckets

For events (air, 8), (rail, 1) and (air, 5), the air group contains eight and five in that order. Allocate a list on first encounter with each distinct key. If every key uses a shared default list, both groups see all three values. Test groups with distinct contents and mutate one after construction to find accidental aliasing. See mutable default arguments for another source of shared storage.

Pick the lightest summary that still supports the query

If the output needs sum by transport mode, air can keep thirteen and rail one. A later request for the original event within air needs full records or another index. For grouped averages, maintain both sum and count because bucket sizes differ. Define whether a missing label becomes a group or is rejected with its record ID. See categorical histograms.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩