Last active
July 30, 2022 17:24
-
-
Save titovanton/2225805da5ccdd788349bbf7f1eef1a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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