Counting Frequencies in a Dictionary

A frequency map associates each observed key with the number of times it occurred.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Update one key per observation
  2. Define how to report missing keys
  3. Trace when a key first appears
  4. Keep an explicit equivalence rule

Update one key per observation

For tea, rice, tea, start with no keys. The first tea creates a count of one. Rice starts at one and the final tea raises its count to two. This is a separate accumulator for every distinct value.

Define how to report missing keys

A missing key can stand for a count of zero when observations create entries as needed. A stored zero can have a different meaning in a predefined catalog, where it indicates that an expected label was observed zero times. Dictionary lookup controls how callers see that difference.[1]

Trace when a key first appears

For readings [4, 1, 4, 4, 1, 8], the count of four moves through one, two and three. The count of one becomes two and eight appears at the end with one. A dictionary increment can read zero as the starting count for an absent key. Keep the invariant that after \(k\) readings all counts sum to \(k\). It catches paths that skip or double-process records. See loop accumulators.

Keep an explicit equivalence rule

Suppose some readings arrive as integer four and some as the string "4". Decide whether the histogram distinguishes them or uses one parsed number. If parsing fails, account for rejected observations so a reported total is still interpretable. Tied counts need a secondary sort key if the report requires reproducible ordering. Test empty data and two distinct keys with the same count. See categorical histograms.

References

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