[英]How to get key of highest value of Python dictionary
Given a message, a python dictionary is returned that looks like this:给定一条消息,返回一个 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"],
}
How can I get the key of the highest value using python?如何使用 python 获得最高值的密钥? In this case, I would want the value 'THREAT' as it has the highest summaryScore value of 0.043225855.在这种情况下,我想要值“威胁”,因为它具有最高的 summaryScore 值 0.043225855。
The max()
builtin accepts a key
argument. max()
内置函数接受一个key
参数。
message = {
"attributeScores": {
# ...
},
}
highest_attribute = max(
message["attributeScores"].items(),
key=lambda item: item[1]["summaryScore"]["value"],
)
print(highest_attribute)
prints out the item (pair of key and value) you seek:打印出您寻找的项目(一对键和值):
('THREAT', {'spanScores': [{'begin': 0, 'end': 2, 'score': {'value': 0.043225855, 'type': 'PROBABILITY'}}], 'summaryScore': {'value': 0.043225855, 'type': 'PROBABILITY'}})
You can find the highest value from dictionary in different way.您可以以不同的方式从字典中找到最高值。 Below I have added two approaches:下面我添加了两种方法:
Taking the attributeScores dictionary from your dictionary从您的字典中获取 attributeScores 字典
x = d["attributeScores"]
Way 1: Applying loop on attributeScores dictioanry方式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: output:
('THREAT', {'spanScores': [{'begin': 0, 'end': 2, 'score': {'value': 0.043225855, 'type': 'PROBABILITY'}}], 'summaryScore': {'value': 0.043225855, 'type': 'PROBABILITY'}})
Way 2: Using lambda function attributeScores dictionary方式2:使用 lambda function attributeScores 字典
max(x.items(), key = lambda k : k[1]['summaryScore']['value'])
output: output:
('THREAT', {'spanScores': [{'begin': 0, 'end': 2, 'score': {'value': 0.043225855, 'type': 'PROBABILITY'}}], 'summaryScore': {'value': 0.043225855, 'type': 'PROBABILITY'}})
Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.