python - 如何获取Python字典最高值的键
问题描述
给定一条消息,返回一个 Python 字典,如下所示:
{
"attributeScores": {
"SEVERE_TOXICITY": {
"spanScores": [
{
"begin": 0,
"end": 2,
"score": {"value": 0.012266473, "type": "PROBABILITY"},
}
],
"summaryScore": {"value": 0.012266473, "type": "PROBABILITY"},
},
"THREAT": {
"spanScores": [
{
"begin": 0,
"end": 2,
"score": {"value": 0.043225855, "type": "PROBABILITY"},
}
],
"summaryScore": {"value": 0.043225855, "type": "PROBABILITY"},
},
"IDENTITY_ATTACK": {
"spanScores": [
{
"begin": 0,
"end": 2,
"score": {"value": 0.022005383, "type": "PROBABILITY"},
}
],
"summaryScore": {"value": 0.022005383, "type": "PROBABILITY"},
},
},
"languages": ["en"],
"detectedLanguages": ["en"],
}
如何使用 python 获取最高值的键?在这种情况下,我想要值“威胁”,因为它具有最高的 summaryScore 值 0.043225855。
解决方案
max()
内置函数接受一个key
参数。
message = {
"attributeScores": {
# ...
},
}
highest_attribute = max(
message["attributeScores"].items(),
key=lambda item: item[1]["summaryScore"]["value"],
)
print(highest_attribute)
打印出您寻找的项目(一对键和值):
('THREAT', {'spanScores': [{'begin': 0, 'end': 2, 'score': {'value': 0.043225855, 'type': 'PROBABILITY'}}], 'summaryScore': {'value': 0.043225855, 'type': 'PROBABILITY'}})
推荐阅读
- reactjs - UseEffect 挂钩的 Jest 测试用例
- python - vscode无法打开Python交互,出现如下错误
- javascript - 为什么 ReactDnD 插件在 IE 浏览器中不起作用?
- javascript - useEffect - 更新状态时防止无限循环
- amazon-web-services - nginx 日志中的未知请求
- reporting-services - 在 SSRS 中对选定的文本部分使用粗体
- google-apps-script - 历史最高脚本 - 当 A 列中的整数较大时覆盖 B 列
- python - 声音特征属性错误:'rmse'
- c# - 通过复选框更新列和多个更新
- node.js - Axios POST 请求返回附件,存储它会在 Node.js 中给出 mulformed 文件异常