util.dicts.reduce
Similar to list reduce
, this function takes a dictionary and reduces key-value pairs based on a reducing function. The dictionary is iterated through in order.
The function fn
should be in the form def fn(acc=None, key=None, val=None)
. All keyword arguments are mandatory.
Arguments:
def util.dicts.reduce(
d: dict = None, # Dictionary to reduce
fn: function = None, # Reducing function
default: function = None, # Default value
):
Returns the sum generated by the reduction function fn
.
Example:
def red_fn(acc=0, key='', val=''):
return acc + val
# 6
return util.dicts.reduce(
d={
'john': 1,
'bob': 2,
'charles': 3,
},
fn=red_fn,
default=None)