首页 > 解决方案 > 用于嵌套字典的 Python 函数

问题描述

给定字典:

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}

我希望将输出作为字典,键为'a', 'p', ... 并将它们的值作为嵌套字典中的值相加

预期输出:

{'p': 0.025 , 'a' 0.09811 ....}

标签: pythondictionarynested

解决方案


请参阅Is there any pythonic way to combine two dicts(为两者中出现的键添加值)?

使用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)

输出:

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

推荐阅读