lst = [{"id": 1, "name": "ernest"}, .... {"id": 16, name:"gellner"}]
for d in lst:
if "id" in d and d["id"] == 16:
return d
I want to extract the dictionary that the key “id” equals to “16” from the list.
Is there a more pythonic way of this?
Thanks in advance
Riffing on existing answers to get out of the comments:
Consider using a generator expression when you only need the first matching element out of a sequence:
This is a pattern you’ll see in my code often. This will raise a
StopIterationif it turns out there weren’t any items inlstthat matched the condition. When that’s expected to happen, you can either catch the exception:Or better yet, just unroll the whole thing into a for-loop that stops
(the
else:clause only gets run if the for loop exhausts its input, but gets skipped if the for loop ends becausebreakwas used)