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

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

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 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