hbutils.collection.structural
- Overview:
Structural operations module providing utilities for flattening and walking through nested data structures. This module includes functions for flattening sequences and nested structures (dictionaries, lists, tuples), as well as walking through nested structures to extract paths and values.
sq_flatten
- hbutils.collection.structural.sq_flatten(s)[source]
Flatten a nested sequence into a single-level list.
This function recursively flattens nested lists and tuples into a single flat list, preserving the order of elements.
- Parameters:
s (Union[list, tuple]) – The given sequence to flatten (can contain nested lists and tuples).
- Returns:
Flattened sequence as a list.
- Return type:
list
- Examples::
>>> from hbutils.collection import sq_flatten >>> sq_flatten([1, 2, [3, 4], [5, [6, 7], (8, 9, 10)], 11]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
nested_walk
- hbutils.collection.structural.nested_walk(s) Iterator[Tuple[Tuple[int | str, ...], object]][source]
Walk through a nested structure and yield paths and values for all leaf elements.
This function traverses nested dictionaries, lists, and tuples, yielding a tuple containing the path (as a tuple of keys/indices) and the value for each leaf element.
- Parameters:
s (Union[dict, list, tuple, object]) – Given nested structure to walk through.
- Returns:
Iterator yielding tuples of (path, value) for each leaf element.
- Return type:
Iterator[Tuple[Tuple[Union[int, str], …], object]]
- Examples::
>>> from hbutils.collection import nested_walk >>> for p, v in nested_walk({'a': 1, 'b': ['c', 'd', {'x': (3, 4), 'y': 'f'}]}): ... print(p, v) ... ('a',) 1 ('b', 0) c ('b', 1) d ('b', 2, 'x', 0) 3 ('b', 2, 'x', 1) 4 ('b', 2, 'y') f
nested_flatten
- hbutils.collection.structural.nested_flatten(s) List[Tuple[Tuple[int | str, ...], object]][source]
Flatten a nested structure into a list of (path, value) tuples.
This function converts a nested structure (dictionaries, lists, tuples) into a flat list where each element is a tuple containing the path to a leaf element and its value.
- Parameters:
s (Union[dict, list, tuple, object]) – Given nested structure to flatten.
- Returns:
List of tuples containing (path, value) for each leaf element.
- Return type:
List[Tuple[Tuple[Union[int, str], …], object]]
- Examples::
>>> from hbutils.collection import nested_flatten >>> print(nested_flatten({'a': 1, 'b': ['c', 'd', {'x': (3, 4), 'y': 'f'}]})) [(('a',), 1), (('b', 0), 'c'), (('b', 1), 'd'), (('b', 2, 'x', 0), 3), (('b', 2, 'x', 1), 4), (('b', 2, 'y'), 'f')]