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

262
Vistas
What's the shortest way to find a dict in a list?
[o for o in a if o['k'] == v][0]

This miserable line of code requires 3 references to the dict o. Compare the JavaScript version, with not a single direct reference to o:

a.find(({ k }) => k == v)

It not only requires fewer references, it uses fewer characters without broaching unreadable code-golf territory.

Is there a shorter way to find a dict in a list in Python comparable to this?

Perhaps Python doesn't even have an equivalent to JavaScript's Array.prototype.find. The first line of code seems to be more equivalent to Array.prototype.filter.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can write it like this instead:

result = next(filter(lambda o: o['k'] == v, a))

It's not exactly shorter, but it is in some ways less repetitive.

Documentation for next and filter is on this page; you can find a tutorial on lambda functions here.

Even if you decide to stick with the comprehension-style syntax, by the way, you should probably refactor your code into a generator expression rather than a list comprehension, since there is no need to build the list in memory if you only need one item from it:

result = next(o for o in a if o['k'] == v)
about 4 years ago · Juan Pablo Isaza 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