I have a partially weird question. Basically 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 essentially to auto convert the object to a string before its used as a key. Is this possible?
Thanks so much.
>Solution :
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