dictutils.ops.reduce_byΒΆ

dictutils.ops.reduce_by(items, key, *, zero, reduce, map=<function <lambda>>)[source]ΒΆ

Reduce items by key using custom reducer function.

Parameters:
  • items (Iterable[Any]) – Collection to reduce

  • key (Union[str, Callable[[Any], Any]]) – Path string or function to extract grouping key

  • zero (Any) – Initial value for reduction

  • reduce (Callable[[Any, Any], Any]) – Binary function to combine values

  • map (Callable[[Any], Any]) – Function to transform items before reduction

Return type:

dict[Any, Any]

Returns:

Dictionary mapping keys to reduced values

Example

>>> import json
>>> sales = [
...     {"region": "North", "amount": 100},
...     {"region": "South", "amount": 200},
...     {"region": "North", "amount": 150}
... ]
>>> result = reduce_by(sales, "region", zero=0, reduce=lambda a, b: max(a, b),
...                   map=lambda x: x["amount"])
>>> print(json.dumps(result, indent=4))
{
    "North": 150,
    "South": 200
}