0

Given a dictionary :

dic = {
    2: {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09311},
    7: {'r': 0.186, 's': 0.148, 'd': 0.145, 'a': 0.005},
    8: {'r': 0.1, 's': 0.2}

I want the output as a dictionary with key as 'a', 'p', ... and their values as the addition of their values in a nested dictionary

Expected output:

{'p': 0.025 , 'a' 0.09811 ....}
wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

0

Try the following:

dic = {2: {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09311}, 7: {'r': 0.186, 's': 0.148, 'd': 0.145, 'a': 0.005},8:{'r':0.1, 's':0.2}}

res = {}

for d in dic.values():
    for k, v in d.items():
        res[k] = res.get(k, 0.0) + v

print(res) # {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09811, 'r': 0.28600000000000003, 's': 0.348, 'd': 0.145}

In particular, dict.get(key, value) returns dict[key] if the latter is present, and value otherwise.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

See Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Use collections.Counter

from collections import Counter

dic = {2: {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09311},
       7: {'r': 0.186, 's': 0.148, 'd': 0.145, 'a': 0.005},
       8: {'r': 0.1, 's': 0.2}}

res = dict(sum([Counter(d) for d in dic.values()], Counter()))
print(res)

output:

{'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09811, 'r': 0.28600000000000003, 's': 0.348, 'd': 0.145}
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57