From cd39be8fc777910e150c3f6db40a84bcd88d7d33 Mon Sep 17 00:00:00 2001 From: Suraj Shetty Date: Wed, 31 Oct 2018 08:08:23 +0530 Subject: [PATCH] Add find & find_all utility function Co-authored-by: Aditya Hase --- frappe/core/utils.py | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/frappe/core/utils.py b/frappe/core/utils.py index 01f18c16d0..89aba20cd8 100644 --- a/frappe/core/utils.py +++ b/frappe/core/utils.py @@ -30,5 +30,39 @@ def set_timeline_doc(doc): doc.timeline_doctype = doctype doc.timeline_name = name - else: - return \ No newline at end of file + 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 \ No newline at end of file