Created
April 29, 2020 07:28
-
-
Save onekiloparsec/f23eeb69f67cb087b9014e02011b8bef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.