0

I have the following filter in my code:

id = 4     
for result in filter(lambda list: list['id'] == id, list):
    pass #do something with the result

List is a list of dictionaries. It may be that there are duplicates in the list. How can I limit the number of results to 1?

VengaVenga
  • 680
  • 1
  • 10
  • 13
  • This is not a question about lambda. This is a question about *`filter()`*, or more generally, about iterators. – Martijn Pieters Oct 16 '18 at 11:33
  • You are basically asking: *how to check that an iterator returns at most one element*. – Martijn Pieters Oct 16 '18 at 11:35
  • Or do you want just the first match and don't care if there are more? – Martijn Pieters Oct 16 '18 at 11:36
  • I'm going with the latter explanation for now, and found you a suitable duplicate. TLDR: `result = next(filter(lambda list: list['id'] == id, list), None)` would give you the first match, or `None` if there were no matches. – Martijn Pieters Oct 16 '18 at 11:37
  • Thanks, Martijn, it's exactly the latter I want to achieve, also the other option is also interesting as learning experience (maybe for others). – VengaVenga Oct 16 '18 at 14:19

0 Answers0