我有一个嵌套字典:
{'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)
你可以使用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)
| 归档时间: |
|
| 查看次数: |
1044 次 |
| 最近记录: |