Andy Chen
Andy Chen

Reputation: 85

How to get key of highest value of Python dictionary

Given a message, a python dictionary is returned that looks like this:

{
    "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? In this case, I would want the value 'THREAT' as it has the highest summaryScore value of 0.043225855.

Upvotes: 3

Views: 122

Answers (2)

Tarequzzaman Khan
Tarequzzaman Khan

Reputation: 494

You can find the highest value from dictionary in different way. Below I have added two approaches:

Taking the attributeScores dictionary from your dictionary

x = d["attributeScores"]

Way 1: Applying loop on attributeScores dictioanry

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

Way 2: Using lambda function attributeScores dictionary

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

Thanks

Upvotes: 0

AKX
AKX

Reputation: 169387

The max() builtin accepts a key argument.

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

Upvotes: 9

Related Questions