Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to automatically convert an object into a string before its used as a key in a dictionary – python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading