I just want to complement this answer on how to search a dictionary in both ways.
My answer includes a init method to initialize the TwoWayDict class with a already existing dictionary.
I just want to complement this answer on how to search a dictionary in both ways.
My answer includes a init method to initialize the TwoWayDict class with a already existing dictionary.
Here it is:
class TwoWayDict(dict):
def __init__(self, init_dict):
for key, value in init_dict.items():
dict.__setitem__(self, key, value)
dict.__setitem__(self, value, key)
def __setitem__(self, key, value):
# 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):
dict.__delitem__(self, self[key])
dict.__delitem__(self, key)
def __len__(self):
"""Returns the number of connections"""
return dict.__len__(self) // 2
So now you can initialize a TwoWayDict using a already existenting dictionary.
Have a nice day ^^