用不同的键对嵌套字典中的项进行求和

use*_*653 4 python dictionary

我有一个嵌套字典:

{'apple':  {'a': 1, 'b': 4, 'c': 2},
 'orange': {'a': 4, 'c': 5},
 'pear':   {'a': 1, 'b': 2}}
Run Code Online (Sandbox Code Playgroud)

我想要做的是摆脱外键并对内键的值求和,这样我就有了一个新的字典,如下所示:

{'a': 6, 'b': 6, 'c': 7}
Run Code Online (Sandbox Code Playgroud)

slo*_*oth 7

你可以使用Counter类:

>>> from collections import Counter

>>> d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
>>> sum(map(Counter, d.values()), Counter())
Counter({'c': 7, 'a': 6, 'b': 6})
Run Code Online (Sandbox Code Playgroud)