Bimaps
I was already aware of a type of data structure called “map”. Some programming languages refer to it as a “dictionary”. This type of structure allows me to perform speedy lookups on values using keys. On more than a few occasions, I found myself needing to look up the dictionary’s keys by value. I’d end up creating another dictionary just to act as a reverse-lookup where I stored the values as keys and the keys as values.
Turns out there’s another data structure that accomplishes just that. It’s called a “bimap”. In Python, it’s called bidict.
from bidict import bidict
bimap = bidict({”a”: 1, “b”: 2, “c”: 3})
# Lookup by key.
print(bimap[”a”]) # Output: 1
# Lookup by value.
print(bimap.inverse[1]) # Output: a
bimap[”d”] = 4
print(bimap) # Output: bidict({”a”: 1, “b”: 2, “c”: 3, “d”: 4})
print(bimap.inverse) # Output: bidict({1: “a”, 2: “b”, 3: “c”, 4: “d”})It does require installation, though, of a package called bidict.


