繁体   English   中英

如何获取 Python 字典的最高值键

[英]How to get key of highest value of Python dictionary

给定一条消息,返回一个 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'}})

您可以以不同的方式从字典中找到最高值。 下面我添加了两种方法:

从您的字典中获取 attributeScores 字典

x = d["attributeScores"]

方式1:在attributeScores字典上应用循环

highest = 0
highest_dic ={}
for k in x.items():
    if k[1]['summaryScore']['value'] > highest:
        highest = k[1]['summaryScore']['value']
        highest_dic = k
print(highest_dic)    

output:

('THREAT', {'spanScores': [{'begin': 0, 'end': 2, 'score': {'value': 0.043225855, 'type': 'PROBABILITY'}}], 'summaryScore': {'value': 0.043225855, 'type': 'PROBABILITY'}})

方式2:使用 lambda function attributeScores 字典

max(x.items(), key = lambda k : k[1]['summaryScore']['value'])

output:

('THREAT', {'spanScores': [{'begin': 0, 'end': 2, 'score': {'value': 0.043225855, 'type': 'PROBABILITY'}}], 'summaryScore': {'value': 0.043225855, 'type': 'PROBABILITY'}})

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM