Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 654
unice Avatar asked Nov 29 '22 04:11

unice


1 Answers

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

from operator import itemgetter
max(lst, key=itemgetter('score'))
like image 148
mhyfritz Avatar answered Dec 05 '22 02:12

mhyfritz