Given a one-to-one dictionary (=bijection) generated à la
for key, value in someGenerator:
myDict[key] = value
an inverse lookup dictionary can be trivially created by adding
invDict[value] = key
to the for
loop. But is this a Pythonic way? Should I instead write a class Bijection(dict)
which manages this inverted dictionary in addition and provides a second lookup function? Or does such a structure (or a similar one) already exist?
If you specify a key a second time during the initial creation of a dictionary, then the second occurrence will override the first. Second, a dictionary key must be of a type that is immutable.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
What I've done in the past is created a reversedict
function, which would take a dict and return the opposite mapping, either values to keys if I knew it was one-to-one (throwing exceptions on seeing the same value twice), or values to lists of keys if it wasn't. That way, instead of having to construct two dicts at the same time each time I wanted the inverse look-up, I could create my dicts as normal and just call the generic reversedict
function at the end.
However, it seems that the bidict solution that Jon mentioned in the comments is probably the better one. (My reversedict
function seems to be his bidict's ~
operator).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With