Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to store a twoway dictionary than storing its inverse separate? [duplicate]

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?

like image 372
Tobias Kienzler Avatar asked May 28 '13 13:05

Tobias Kienzler


People also ask

What happens if you use the same key multiple times while creating a dictionary?

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.

Can dictionaries have duplicate keys?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

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).

like image 148
Claudiu Avatar answered Oct 12 '22 02:10

Claudiu