Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda