dictutils.nestagg.nest_agg

dictutils.nestagg.nest_agg(items, keys, *, aggs, include_rows=False, rows_key='rows')[source]

Build a nested dict keyed by keys, with aggregations at the leaves.

Parameters:
  • items (list[Any]) – List of items (dicts/objects) to process

  • keys (list[Union[str, Callable[[Any], Any]]]) –

    List of selectors for grouping. Each can be:

    • String key/attribute name

    • Dotted path like “supplier.name”

    • Callable that takes an item and returns a grouping key

  • aggs (dict[str, Agg]) – Dict of {name: Agg} specifications for leaf aggregations

  • include_rows (bool) – If True, include raw items under rows_key

  • rows_key (str) – Key name for raw rows (when include_rows=True)

Return type:

dict

Returns:

Nested dict with aggregated values at leaves

Example:

items = [
    {"cat": "A", "val": 1},
    {"cat": "A", "val": 2},
    {"cat": "B", "val": 3}
]
aggs = {
    "total": Agg(map=lambda it: it["val"], zero=0),
    "count": Agg(map=lambda it: 1, zero=0)
}
result = nest_agg(items, keys=["cat"], aggs=aggs)
# {"A": {"total": 3, "count": 2}, "B": {"total": 3, "count": 1}}