pythondata-structures

A data-structure for 1:1 mappings in python?


I have a problem which requires a reversable 1:1 mapping of keys to values.

That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique.

x = D[y]
y == D.inverse[x]

The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, there's a recipe here but for a large dictionary it can be very slow.

The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict.

So is there a better structure I can use?


Solution

  • class TwoWay:
        def __init__(self):
           self.d = {}
        def add(self, k, v):
           self.d[k] = v
           self.d[v] = k
        def remove(self, k):
           self.d.pop(self.d.pop(k))
        def get(self, k):
           return self.d[k]