Skip to content

Instantly share code, notes, and snippets.

@fogleman
Created May 1, 2015 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fogleman/f6d1654b6128aa09571f to your computer and use it in GitHub Desktop.
Save fogleman/f6d1654b6128aa09571f to your computer and use it in GitHub Desktop.
Sum Dictionary Tuples
import operator
def merge(dicts):
result = {}
keys = reduce(operator.or_, [set(d) for d in dicts])
for key in keys:
values = [d[key] for d in dicts if key in d]
result[key] = tuple(reduce(operator.add, x) for x in zip(*values))
return result
if __name__ == '__main__':
a = {0: (1, 3, 2), 1: (8, 4, 4), 2: (3, 4, 2)}
b = {0: (5, 5, 6), 1: (3, 7, 6), 2: (1, 9, 5)}
c = {0: (3, 7, 7), 1: (2, 3, 8)}
print merge([a, b, c]) # {0: (9, 15, 15), 1: (13, 14, 18), 2: (4, 13, 7)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment