Created
April 5, 2020 09:03
-
-
Save abhiabhi94/133ec0b1237ebce87f08da0cc92cd8c1 to your computer and use it in GitHub Desktop.
Create a two way dict to be useful for symmetric mapping
This file contains 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 SymmetricMapping(dict): | |
""" | |
Construct a bidirectional mapping when a list of tuple is passed. | |
The mapping is usable as a two way dictionaty which has the same length\ | |
as the original one. | |
Example usage: | |
obj = SymmetricMapping([[(1, "Male"), (2, "Female"), (3, "Non-binary")]]) | |
>>> obj | |
{ | |
1: 'Male', | |
'Male': 1, | |
2: 'Female', | |
'Female': 2, | |
3: 'Non-binary', | |
'Non-binary': 3 | |
} | |
>>> len(obj) | |
3 | |
""" | |
def __init__(self, list_of_tuples): | |
"""Create the dict for items passed""" | |
super(SymmetricMapping, self).__init__() | |
for (key, value) in list_of_tuples: | |
self.__setitem__(key, value) | |
def __setitem__(self, key, value): | |
"""Set items for symmmetric mapping""" | |
# Remove any previous connections with these values | |
if key in self: | |
del self[key] | |
if value in self: | |
del self[value] | |
dict.__setitem__(self, key, value) | |
dict.__setitem__(self, value, key) | |
def __delitem__(self, key): | |
"""Delete connections from both mappings""" | |
dict.__delitem__(self, self[key]) | |
dict.__delitem__(self, key) | |
def __len__(self): | |
"""Returns the number of connections""" | |
return dict.__len__(self) // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment