search#
- search(obj, query='<sc_nested_custom_None>', key='<sc_nested_custom_None>', value='<sc_nested_custom_None>', type='<sc_nested_custom_None>', method='exact', **kwargs)[source]#
Find a key/attribute or value within a list, dictionary or object.
This function facilitates finding nested key(s) or attributes within an object, by searching recursively through keys or attributes. See
sc.iterobj()for more detail.- Parameters:
obj (any) – A dict, list, or object
query (any) – The key or value to search for (or a function or a type); equivalent to setting both
keyandvaluekey (any) – The key to search for
value (any) – The value to search for
type (type) – The type (or list of types) to match against (for values only)
method (str) – if the query is a string, choose how to check for matches: ‘exact’ (test equality), ‘partial’ (partial/lowercase string match), or ‘regex’ (treat as a regex expression)
kwargs (dict) – passed to
sc.iterobj()
- Returns:
A dictionary of matching attributes; like
sc.iterobj(), but filtered to only include matches.
Examples:
# Create a nested dictionary nested = {'a':{'foo':1, 'bar':['moat', 'goat']}, 'b':{'car':3, 'cat':[1,2,4,8]}} # Find keys keymatches = sc.search(nested, 'bar', flatten=True) # Find values val = 4 valmatches = sc.search(nested, value=val).keys()[0] # Returns ('b', 'cat', 2) assert sc.getnested(nested, valmatches) == val # Get from the original nested object # Find values with a function def find(v): return True if isinstance(v, int) and v >= 3 else False found = sc.search(nested, value=find) # Find partial or regex matches found = sc.search(nested, value='oat', method='partial', leaf=True) # Search keys only keys,vals = sc.search(nested, '^.ar', method='regex', verbose=True)
New in version 3.0.0: ability to search for values as well as keys/attributes; “aslist” argumentNew in version 3.1.0: “query”, “method”, and “verbose” keywords; improved searching for listsNew in version 3.2.0: allow type matching; removed “return_values”; renamed “aslist” to “flatten” (reversed)