Skip to content

Instantly share code, notes, and snippets.

@adammartinez271828
Last active August 3, 2016 01:07
Show Gist options
  • Save adammartinez271828/ecd854e04fbc76752176f68352be8f60 to your computer and use it in GitHub Desktop.
Save adammartinez271828/ecd854e04fbc76752176f68352be8f60 to your computer and use it in GitHub Desktop.
Keywise dictionary reduction operator.
def dict_reduce(f, *dicts):
"""
Apply a function f to the values of an iterable of dictionaries by key
Gets a complete set of keys across all dictionaries, then, for each key,
applies f to the list of values of each dictionary for that key.
Args:
f (function): a function that takes an iterable
*dicts: an iterable of dictionaries
Returns:
a dictionary s.t. d[k] = f(d1[k], d2[k], d3[k]...) for all k
"""
reduced_dict = {}
key_sets = (set(d.keys()) for d in dicts)
keys = set.union(*key_sets)
for key in keys:
values = (d[key] for d in dicts if key in d)
reduced_dict[key] = f(*values)
return reduced_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment