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

153
Views
Convertir objeto en clave de diccionario

Me preguntaba si hay una manera fácil de tener esencialmente varias claves en un diccionario para un valor. Un ejemplo de lo que me gustaría lograr es el siguiente:

 class test: key="test_key" def __str__(self): return self.key tester = test() dictionary = {} dictionary[tester] = 1 print(dictionary[tester]) print(dictionary["test_key"])

donde la salida sería:

 >>> 1 >>> 1

Lo que estoy buscando es una forma de convertir automáticamente el objeto en una cadena antes de que se use como clave. es posible?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Personalmente, creo que es mejor convertir explícitamente el objeto en una cadena, por ejemplo

 dictionary[str(tester)] = 1

Dicho esto, si realmente está REALMENTE seguro de querer hacer esto, defina los __hash__ y __eq__ dunder. No es necesario crear una nueva estructura de datos o cambiar el código existente fuera de la definición de clase:

 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

Esto generará:

 1 1
over 4 years ago · Santiago Trujillo Report

0

Es casi seguro que no deberías hacer esto; solo usa dictionary[str(tester)] . Es más legible, menos sorpresas, solo cinco caracteres más para escribir.

Si insistes, esto es lo mejor que se me ocurre.

 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!