Two Dicts Keep A Bidirectional Map In Sync
Two dicts kept in sync give both directions of a lookup; adds and removes must touch both sides and duplicates must be rejected at the entry point.
Code
class TwoWayMap:
# A bidirectional lookup backed by two dicts kept in sync
def __init__(self):
self.forward = {} # key -> value
self.inverse = {} # value -> key
def add(self, key, value):
if key in self.forward or value in self.inverse:
raise ValueError(f"duplicate {key!r} or {value!r}")
self.forward[key] = value
self.inverse[value] = key
def remove(self, key):
value = self.forward.pop(key)
del self.inverse[value]
def by_value(self, value):
return self.inverse[value]
codes = TwoWayMap()
codes.add("user-1", "ALPHA22")
codes.add("user-2", "BRAVO7")
print(codes.forward["user-1"]) # ALPHA22
print(codes.by_value("ALPHA22")) # user-1
codes.remove("user-2")
print("user-2 gone:", "user-2" in codes.forward)
print("BRAVO7 gone:", "BRAVO7" in codes.inverse)
try:
codes.add("user-3", "ALPHA22")
except ValueError as error:
print("rejected:", error)Output
Captured from a sandboxed run of this snippet in the build pipeline.
ALPHA22
user-1
user-2 gone: False
BRAVO7 gone: False
rejected: duplicate 'user-3' or 'ALPHA22'What the demo syncs
TwoWayMap keeps forward, key to value, and inverse, value to key, as two plain dicts. add writes both sides and rejects duplicates up front: re-adding value ALPHA22 raises ValueError with the colliding key and value in the message.
Lookups run in either direction: codes.forward[“user-1”] prints ALPHA22 and by_value goes backwards. remove pops the key and deletes the inverse entry in the same step, which is why both printed membership checks come back False after user-2 is removed.
Practical notes
- Every mutation must touch both dicts or the map drifts.
- The duplicate check covers both directions before either write.
Interactive Tools for This Topic
FAQ
- Why reject duplicates at the entry point?
- A repeated value would overwrite the inverse entry and orphan the old key; raising ValueError at add time keeps both dicts consistent, as the rejected user-3 line shows.
Report a problem with this exampleOpens a pre-filled issue on GitHub.