首页 > 解决方案 > 如何获取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。

标签: python

解决方案


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'}})

推荐阅读