dictutils.nestagg.Agg

class dictutils.nestagg.Agg(map, zero=None, reduce=<built-in function add>, skip_none=True, finalize=None)[source]

Declarative aggregate specification.

Parameters:
  • map (Callable[[Any], Any]) – Function that extracts a value from each item to aggregate

  • zero (Any) – Identity element (value or callable). If None, first mapped value seeds the total

  • reduce (Callable[[Any, Any], Any]) – Function to combine values (default: operator.add)

  • skip_none (bool) – If True, ignore mapped None values (default: True)

  • finalize (Optional[Callable[[Any], Any]]) – Optional function to transform the final aggregated value

Example

Sum values:

Agg(map=lambda x: x["amount"], zero=0)

Count items:

Agg(map=lambda x: 1, zero=0, reduce=operator.add)

Calculate average:

Agg(
    map=lambda x: (x["val"], 1),
    zero=(0, 0),
    reduce=lambda a, b: (a[0] + b[0], a[1] + b[1]),
    finalize=lambda x: x[0] / x[1] if x[1] > 0 else 0
)
__init__(map, zero=None, reduce=<built-in function add>, skip_none=True, finalize=None)
Parameters:
Return type:

None

Methods

__init__(map[, zero, reduce, skip_none, ...])

reduce(a, b, /)

Same as a + b.

Attributes

finalize

skip_none

zero

map