Grouping Values by a Computed Key

To group values, compute one key per item and append the item to the collection for that key.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Trace by first letter
  2. Check bucket ownership
  3. Sort and group solve different problems
  4. Keep the state your final question requires

Trace by first letter

Given pear, apple, plum, the buckets contain pear then plum under p and apple under a. The order within a bucket follows the visit order. Hashable key rules describe what can be used directly for dictionary groups.

Check bucket ownership

If two keys use the same mutable list, adding a pear to one group makes it appear in both. Create an independent list for each new key and test one group with two items and another with one. Mutable values explain this failure without changing the grouping rule.[1]

Sort and group solve different problems

Suppose four checkout records give the pairs (north, 3), (west, 2), (north, 5) and (east, 1). A grouping dictionary maps north to [3, 5] even though a west record interrupts the input. A loop that closes the current group whenever the region changes would produce two separate north runs. Such a loop works when records are already sorted by region or when the boundaries themselves carry meaning. Sorting the entire source first may be infeasible for a stream. See contiguous runs for the consecutive case and compare its memory use to retaining a collection per key.

Keep the state your final question requires

If all you report is regional volume, keep north at eight using a running sum, with a counter only if you also need a mean. Preserving both original north records is necessary if people can inspect individual checkouts in the output. A missing region needs an explicit policy. Group it under a designated unknown category if it remains part of the total, or reject the record with its line number if a region is mandatory. Test two equal regions separated by another region, a new region on the final record, and input with no records. The running-total pattern is the state update used inside each regional bucket.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩