uni*_*ice 4 python dictionary list
我有一个字典列表,是否可以获得具有最高分数键值的字典或其索引?这是清单.
lst= [{'name':'tom','score':5},{'name':'jerry','score':10},{'name':'jason','score':8}]
Run Code Online (Sandbox Code Playgroud)
如果应该返回
{'name':'jerry','score':10}
Run Code Online (Sandbox Code Playgroud)
谢谢.
使用a lambda作为key参数的替代方法max是operator.itemgetter:
from operator import itemgetter
max(lst, key=itemgetter('score'))
Run Code Online (Sandbox Code Playgroud)
内置函数max()采用可选key功能,可以以下列形式提供lambda:
>>> max(lst, key=lambda x:x['score'])
{'score': 10, 'name': 'jerry'}
Run Code Online (Sandbox Code Playgroud)