Created
May 1, 2015 15:58
-
-
Save fogleman/f6d1654b6128aa09571f to your computer and use it in GitHub Desktop.
Sum Dictionary Tuples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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