unice
unice

Reputation: 2842

How to get the dictionary with the highest value in a list of dicts

I have a list of dictionaries. Is it possible to get the dictionary or its index that has the highest score key value? Here is the list:

 lst = [{'name': 'tom', 'score': 5}, 
        {'name': 'jerry', 'score': 10},
        {'name': 'jason', 'score': 8}]

It should return:

{'name': 'jerry', 'score': 10}

Upvotes: 4

Views: 1746

Answers (4)

mhyfritz
mhyfritz

Reputation: 8532

An alternative to using a lambda for the key argument to max, is operator.itemgetter:

from operator import itemgetter
max(lst, key=itemgetter('score'))

Upvotes: 9

Petar Ivanov
Petar Ivanov

Reputation: 93090

lst= [{'name':'tom','score':5},{'name':'jerry','score':10},{'name':'jason','score':8}]

print max(lst, key=lambda x: x['score'])

Upvotes: 2

Thomas
Thomas

Reputation: 182073

My preferred way would be to use a lambda to extract the score:

>>> lst= [{'name':'tom','score':5},{'name':'jerry','score':10},{'name':'jason','score':8}]
>>> max(lst, key=lambda d: d['score'])
{'score': 10, 'name': 'jerry'}

Upvotes: 3

johnsyweb
johnsyweb

Reputation: 141988

The built-in function, max() takes an optional key function, which can be supplied in the form of a lambda:

>>> max(lst, key=lambda x:x['score'])
{'score': 10, 'name': 'jerry'}

Upvotes: 8

Related Questions