Skip to content

Instantly share code, notes, and snippets.

@onekiloparsec
Created April 29, 2020 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onekiloparsec/f23eeb69f67cb087b9014e02011b8bef to your computer and use it in GitHub Desktop.
Save onekiloparsec/f23eeb69f67cb087b9014e02011b8bef to your computer and use it in GitHub Desktop.
def find_first_in_list(objects, **kwargs):
return next((obj for obj in objects if
len(set(obj.keys()).intersection(kwargs.keys())) > 0 and
all([obj[k] == v for k, v in kwargs.items() if k in obj.keys()])),
None)
@onekiloparsec
Copy link
Author

Usage:

obj = find_first_in_list(list_of_dict, name='Hello', key=23)

If any key provided is not in keys of list of dict it is skipped. However, the function ensures there is at least one valid key used to compare. This implementation ensure you won't hit KeyError when passing an unknown key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment