Joining Two Collections by Key in Memory

A lookup map can associate items from two collections efficiently when join keys and multiplicities are understood.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a small join
  2. Handle an unmatched key
  3. Derive the output multiplicity by key
  4. Choose how unmatched input should appear

Trace a small join

A list of orders refers to customer IDs 4, 8, and 4. A map from customer ID to name can enrich each row while preserving all three orders. Use composite keys if multiple fields define the relationship.

Handle an unmatched key

If customer 8 is absent, the join can skip the order, keep it with a missing customer, or report inconsistent input. The function contract should state which rule applies. Duplicate customer keys must also be addressed if each order expects a single match.[1]

Derive the output multiplicity by key

Suppose left events are (A, open) and (A, close). The right side contains (A, east) and (A, west). An inner join matching only A produces four pairs. Building an index that stores one right row per key drops half of them. If the right key must be unique, detect the duplicate when building the index. See building a reverse index for the one-versus-many distinction.

Choose how unmatched input should appear

A set of right keys suffices when the question is which left events have any match. If output also shows the right-side value, use an index carrying the row or rows. If left rows without a match must remain in the report, provide an explicit absent-right representation. Test duplicate keys on both sides, one unmatched left item and a right row unused by any left item. See dictionary lookups.

References

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