python - 用于嵌套字典的 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 ....}
解决方案
请参阅Is there any pythonic way to combine two dicts(为两者中出现的键添加值)?
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}
推荐阅读
- html - 更改 Bootstrap Navbar 3.4.1 的字体颜色
- haskell - 如何调试 SMT-Lib 输出中缺少的变量?
- android - 以编程方式在android中启用nfc
- c++ - 为什么 std::iterator 无法访问该函数
- html - 如何在任何屏幕尺寸中制作固定间距位置
- laravel - 在 laravel 中更改时间格式
- r - 我可以在 R 中使用带有条件的 mutate 吗?
- javascript - Jquery - 选择最接近所选元素的所有复选框
- ms-access - 经典 ASP、Visual Basic 和 ADODB 记录集
- php - 如何在 Laravel 的 Welcome.blade.php 中显示我的数据库中的数据?