python - 如何获取嵌套字典中的最大值以及包含它的键?

标签 python dictionary

我有以下字典,我得到每个嵌套字典中的最大值,但我也想获取包含它的键。 我怎样才能得到 key ?

字典:

{0: {'No': 0.0008701660440099657, 'Yes': 0.00041988149400856126},
 1: {'No': 0.00030532988393349125, 'Yes': 0.0004650428587258767},
 2: {'No': 0.0009029060356133256, 'Yes': 0.0007394058270439404},
 3: {'No': 5.692242884555282e-05, 'Yes': 0.0005919332682707075},
 4: {'No': 0.00015013263827995824, 'Yes': 0.00013704067699909492},
 5: {'No': 0.0006475515553117131, 'Yes': 0.000398292472360402},
 6: {'No': 0.00015299971518718442, 'Yes': 0.000636069387240845},
 7: {'No': 0.0003432474070424342, 'Yes': 0.0001701115953231753},
 8: {'No': 0.00029659442779058097, 'Yes': 0.0001243229615986186},
 9: {'No': 0.0002346339088222795, 'Yes': 4.1301441738705087e-05}}

获得最大值的代码:

    for i in range(len(res_dic)):
        print(max(res_dic[i].values()))

预期输出:

No, 0.0008701660440099657

最佳答案

尝试将 maxkey 一起使用:

for i in range(len(res_dic)):
    x = max(res_dic[i], key=res_dic[i].get)
    print(x, res_dic[i][x])

输出:

No 0.0008701660440099657
Yes 0.0004650428587258767
No 0.0009029060356133256
Yes 0.0005919332682707075
No 0.00015013263827995824
No 0.0006475515553117131
Yes 0.000636069387240845
No 0.0003432474070424342
No 0.00029659442779058097
No 0.0002346339088222795

关于python - 如何获取嵌套字典中的最大值以及包含它的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69551426/

相关文章:

Python将文件从远程机器移动到本地

python - 在python中对字符串值进行排序

database - 寻找阿拉伯语词典数据库

c# - 在 C# 中缓存存储字典的最佳方法

python - 来自 TimeGrouper 的组从第一个索引开始

Python,导入模块

python - 如何在 django 中创建字典键值对

xcode - 在 NSUserDefaults 中存储字典导致 EXC_BAD_ACCESS

python - 在 python 中跟踪图像

python - Tkinter 和多线程