Reputation: 2842
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
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
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
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