Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Converting object to dictionary key

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!