Add find & find_all utility function

Co-authored-by: Aditya Hase <aditya@adityahase.com>
This commit is contained in:
Suraj Shetty 2018-10-31 08:08:23 +05:30
parent 09a50942b7
commit cd39be8fc7

View file

@ -30,5 +30,39 @@ def set_timeline_doc(doc):
doc.timeline_doctype = doctype
doc.timeline_name = name
else:
return
else:
return
def find(list_of_dict, match_function):
'''Returns a dict in a list of dicts on matching the conditions
provided in match function
Usage:
list_of_dict = [{'name': 'Suraj'}, {'name': 'Aditya'}]
required_dict = find(list_of_dict, lamda d: d['name'] == 'Aditya')
'''
for entry in list_of_dict:
if match_function(entry):
return entry
return None
def find_all(list_of_dict, match_function):
'''Returns all matching dicts in a list of dicts.
Uses matching function to filter out the dicts
Usage:
colored_shapes = [
{'color': 'red', 'shape': 'square'},
{'color': 'red', 'shape': 'circle'},
{'color': 'blue', 'shape': 'triangle'}
]
red_shapes = find_all(colored_shapes, lamda d: d['color'] == 'red')
'''
found = []
for entry in list_of_dict:
if match_function(entry):
found.append(entry)
return found