search#
- search(obj, query='<sc_nested_custom_None>', key='<sc_nested_custom_None>', value='<sc_nested_custom_None>', aslist=True, method='exact', return_values=False, verbose=False, _trace=None, **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.
- Parameters:
obj (any) – A dict, list, or object
query (any) – The key or value to search for (or a function); equivalent to setting both
key
andvalue
key (any) – The key to search for
value (any) – The value to search for
aslist (bool) – return entries as a list (else, return as a string)
method (str) – choose how to check for matches: ‘exact’ (test equality), ‘partial’ (partial/lowercase string match), or ‘regex’ (treat as a regex expression)
return_values (bool) – return matching values as well as keys
verbose (bool) – whether to print details of the search
_trace – Not for user input - internal variable used for recursion
kwargs (dict) – passed to
sc.iterobj()
- Returns:
A list of matching attributes. The items in the list are the Python strings (or lists) used to access the attribute (via attribute, dict, or listindexing).
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', aslist=False) # Find values val = 4 valmatches = sc.search(nested, value=val, aslist=True) # Returns [['b', 'cat', 2]] assert sc.getnested(nested, valmatches[0]) == 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, key='oat', method='partial') # Search keys only keys,vals = sc.search(nested, '^.ar', method='regex', return_values=True, 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 lists