datopy.modeling.apply_recursive#
- apply_recursive( ) dict[str | int, Any] | Any[source]#
Convert a nested data structure (with explicit or implied key/value pairs) into a tree-like dictionary, applying a given function to terminal values.
- Parameters:
func (Callable[…, Any]) – _description_
obj – _description_
- Returns:
_description_
- Return type:
Examples
>>> from datopy.modeling import apply_recursive
Define the data
>>> nested_data = {'type': 'album', 'url': 'link.com', 'audio_features': [ ... {'loudness': -11.4, 'duration_ms': 251}, ... {'loudness': -15.5, 'duration_ms': 284}]} >>> print(nested_data) {'type': 'album', 'url': 'link.com', 'audio_features': [{'loudness': -11.4, 'duration_ms': 251}, {'loudness': -15.5, 'duration_ms': 284}]}
Convert to json-friendly representation
>>> serialized = apply_recursive(str, nested_data) >>> print(serialized) {'type': 'album', 'url': 'link.com', 'audio_features': {1: {'loudness': '-11.4', 'duration_ms': '251'}, 2: {'loudness': '-15.5', 'duration_ms': '284'}}}
Convert to field/type pairs
>>> schema = apply_recursive(lambda x: type(x).__name__, nested_data) >>> print(schema) {'type': 'str', 'url': 'str', 'audio_features': {1: {'loudness': 'float', 'duration_ms': 'int'}, 2: {'loudness': 'float', 'duration_ms': 'int'}}}