Building a Reverse Index from a Mapping
A reverse mapping relates values back to their original keys. Repeated values can require multiple keys per reverse entry.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Check for a collision
Map two students to the same project and one to another project. Inversion to a single student per project overwrites one assignment. A map from project to a list of students retains both. Use grouped records to construct that structure.
Define stable order when useful
If project displays should keep assignment order, append names while traversing the source assignments in that order. If a student can appear multiple times, decide whether to deduplicate the list. Dictionary insertion order addresses the order of the project keys themselves.[1]
Trace a many-to-one mapping before choosing the result type
Suppose A and C belong to red while B belongs to blue. A comprehension storing one key per color would keep only the last red key. A reverse index needs red mapped to A and C, and blue to B. If the problem requires a mathematical inverse delivering one key, reject duplicate target values explicitly. Test the many-to-one case before accepting a single-key inverse. See grouping records with maps.
Keep the reverse direction consistent under edits
If C changes to blue, remove C from the red bucket and add it to blue. Decide whether empty buckets are observable. If the mapping is the authoritative version and writes are rare, rebuilding the reverse index can avoid partially applied updates. A maintained index pays off when readers repeatedly ask for membership. Include updates and deletion in tests. See two-pass index building.