datopy.modeling.apply_recursive#
- apply_recursive( ) dict[str | int, Any] | Any[source]#
Apply
functo each terminal value in a nested data structure.Valid nested data structures include those with explicit or implied key/value pairs.
- Parameters:
func (Callable[…, Any]) – _description_.
obj – _description_.
- Returns:
A tree-like dictionary representation of the transformed
obj.- Return type:
Examples
>>> from datopy.modeling import apply_recursive >>> import pprint
Define the data
>>> nested_data = { ... 'type': 'album', 'url': 'link.com', 'audio_features': [ ... {'loudness': -11.4, 'duration_ms': 251}, ... {'loudness': -15.5, 'duration_ms': 284} ... ] ... } >>> pprint.pp(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) >>> pprint.pp(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) >>> pprint.pp(schema) {'type': 'str', 'url': 'str', 'audio_features': {1: {'loudness': 'float', 'duration_ms': 'int'}, 2: {'loudness': 'float', 'duration_ms': 'int'}}}