python-benedict/benedict/core/search.py

31 lines
1006 B
Python
Raw Normal View History

from benedict.core.traverse import traverse
from benedict.utils import type_util
def _get_term(value, case_sensitive):
v_is_str = type_util.is_string(value)
v = value.lower() if (v_is_str and not case_sensitive) else value
2021-10-12 12:27:35 +00:00
return (v, v_is_str)
def _get_match(query, value, exact, case_sensitive):
q, q_is_str = _get_term(query, case_sensitive)
v, v_is_str = _get_term(value, case_sensitive)
# TODO: add regex support
2020-02-07 10:42:08 +00:00
if q_is_str and v_is_str and not exact:
return q in v
2020-02-07 10:42:08 +00:00
return q == v
2021-10-12 12:27:35 +00:00
def search(d, query, in_keys=True, in_values=True, exact=False, case_sensitive=True):
items = []
def _search_item(item_dict, item_key, item_value):
2021-10-12 12:27:35 +00:00
match_key = in_keys and _get_match(query, item_key, exact, case_sensitive)
match_val = in_values and _get_match(query, item_value, exact, case_sensitive)
if any([match_key, match_val]):
2021-10-12 12:27:35 +00:00
items.append((item_dict, item_key, item_value))
traverse(d, _search_item)
return items