Skip to content

Instantly share code, notes, and snippets.

@titovanton
Last active July 30, 2022 17:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save titovanton/2225805da5ccdd788349bbf7f1eef1a8 to your computer and use it in GitHub Desktop.
Save titovanton/2225805da5ccdd788349bbf7f1eef1a8 to your computer and use it in GitHub Desktop.
class BiDict(object):
'''
Maps both directions: key->value and value->key
Requires both keys and values are unique. If you pass duplication,
then key/value be overwritten and you get not what expected.
'''
origin = {} # counters the {key->key} case
bidict = {}
def __init__(self, **kwargs):
for key, value in kwargs.items():
self.origin[key] = value
self.bidict[key] = value
self.bidict[value] = key
def __getitem__(self, key):
return self.bidict[key]
def __setitem__(self, key, value):
# Remove any previous connections with these values
if key in self.origin:
self.__delitem__(key)
if value in self.origin:
self.__delitem__(value)
self.origin[key] = value
self.bidict[key] = value
self.bidict[value] = key
def __delitem__(self, key):
del self.bidict[key]
del self.bidict[self.origin[key]]
del self.origin[key]
def __len__(self):
return len(self.origin)
def __iter__(self):
return self.origin.__iter__()
def items(self):
return self.origin.items()
def keys(self):
return self.origin.keys()
def values(self):
return self.origin.values()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment