Add find & find_all utility function
Co-authored-by: Aditya Hase <aditya@adityahase.com>
This commit is contained in:
parent
09a50942b7
commit
cd39be8fc7
1 changed files with 36 additions and 2 deletions
|
|
@ -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
|
||||
Loading…
Add table
Reference in a new issue