search#
- class search(obj, key='sc.search() placeholder', value='sc.search() placeholder', aslist=True, _trace=None)[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
key (any) – The key to search for (or a function)
value (any) – The value to search for
aslist (bool) – return entries as a list (else, return as a string)
_trace – Not for user input - internal variable used for recursion
- 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':2}, 'b':{'car':3, 'cat':[1,2,4,8]}} # Find keys keymatches = sc.search(nested, 'bar', aslist=False) # Returns ['["a"]["bar"]', '["b"]["bar"]'] # 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) # Returns [['b', 'cat', 2]]
New in version 3.0.0: ability to search for values as well as keys/attributes; “aslist” argument