I have come across this case a few times now: I have an array which contains an element I want and I want to select that element without knowing the index, and instead knowing some desired property (maybe it is a list of dictionaries and I want the dictionary elem
such that elem['foo'] == 'bar'
).
A solution I have is do a filter (or more pythonically, a list comprehension) and then take the first element (often times I know that the filtered list will be a singleton, so taking the first is taking the only).
Ex. Given a list x = [{'foo': 'bar_1'}, {'foo': 'bar_2'}]
, I want the element whose 'foo'
value is 'bar2'
. So I do this :
y = [elem for elem in x if elem['foo'] == 'bar_2'][0]
Is there a more standard way of doing this? It seems like a very simple and common use case.