1 回答
TA贡献1836条经验 获得超13个赞
您可以对内部字典的值使用Counter:
from collections import Counter
d1 = {'Breda': {'Fuery': {'anger': 1},
'Havoc': {'anticipation': 1, 'surprise': 1},
'Hawkeye': {'anticipation': 2}},
'Fuery': {'Breda': {'anticipation': 2, 'surprise': 1},
'Mustang': {'fear': 4}},
'Havoc': {'Breda': {'joy': 1},
'Gloria': {'joy': 1},
'Hawkeye': {'anticipation': 4, 'joy': 1, 'surprise': 1},
'Mustang': {'surprise': 1}},
'Hawkeye': {'Hawkeye': {'joy': 2, 'trust': 1},
'Mustang': {'anger': 1,
'joy': 6,
'surprise': 4,
'trust': 1}},
'Mustang': {'Everyone': {'anger': 2},
'Fuery': {'anger': 3, 'surprise': 1},
'Hawkeye': {'anger': 1,
'joy': 6,
'surprise': 1,
'trust': 1},
'Mustang': {'joy': 2, 'trust': 1},
'the team': {'anger': 1}}}
result = {key: dict(sum(map(Counter, inner.values()), Counter())) for key, inner in d1.items()}
print(result)
输出
{'Havoc': {'joy': 3, 'surprise': 2, 'anticipation': 4}, 'Mustang': {'joy': 8, 'trust': 2, 'anger': 7, 'surprise': 2}, 'Hawkeye': {'joy': 8, 'surprise': 4, 'anger': 1, 'trust': 2}, 'Breda': {'surprise': 1, 'anger': 1, 'anticipation': 3}, 'Fuery': {'fear': 4, 'surprise': 1, 'anticipation': 2}}
该语句sum(map(Counter, inner.values()), Counter())将每个内部字典转换为一个 Counter,然后使用sum将它们组合在一起。这是可以做到的,因为 Counter 实现了加法,例如:
Counter({'anticipation': 2}) + Counter({'anticipation': 1, 'surprise': 1})
返回:
Counter({'anticipation': 3, 'surprise': 1})
更新
如果您想要每个键的总数,只需添加以下几行:
total = { key : sum(inner.values()) for key, inner in result.items() }
print(total)
输出
{'Hawkeye': 15, 'Mustang': 19, 'Fuery': 7, 'Havoc': 9, 'Breda': 5}
添加回答
举报