Home > Software engineering >  What's the shortest way to find a dict in a list?
What's the shortest way to find a dict in a list?

Time:10-04

[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 less references, it uses less 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.

CodePudding user response:

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 into 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)
  • Related