Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda