I was wondering if there is an easy way to essentially have multiple keys in a dictionary for one value. An example of what I would like to achieve is as following:
class test:
key="test_key"
def __str__(self):
return self.key
tester = test()
dictionary = {}
dictionary[tester] = 1
print(dictionary[tester])
print(dictionary["test_key"])
where the output would be:
>>> 1
>>> 1
What I'm looking for is a way to automatically convert the object to a string before its used as a key. Is this possible?
CodePudding user response:
Personally, I think it's better to explicitly cast the object to a string, e.g.
dictionary[str(tester)] = 1
That being said, if you're really really REALLY sure you want to do this, define the __hash__
and __eq__
dunder methods. No need to create a new data structure or change the existing code outside of the class definition:
class test:
key="test_key"
def __hash__(self):
return hash(self.key)
def __eq__(self, other):
if isinstance(other, str):
return self.key == other
return self.key == other.key
def __str__(self):
return self.key
This will output:
1
1
CodePudding user response:
It is almost certain you should not do this; just use dictionary[str(tester)]
. It is more readable, less surprises, only five characters more to write.
If you insist though, this is the best I can think of
class StrKeyedDict(dict):
def __getitem__(self, key):
return super().__getitem__(str(key))
def __setitem__(self, key, value):
super().__setitem__(str(key), value)
# ... do all the other methods that mess with the key
class Test:
key="test_key"
def __str__(self):
return self.key
tester = Test()
dictionary = StrKeyedDict()
dictionary[tester] = 1
print(dictionary["test_key"])
# => 1