[英]How to get whole dict with max value of a common key in a list of dicts
I have a list of dicts like below: 我有一个如下所示的词典列表:
lod = [
{'name': 'Tom', 'score': 60},
{'name': 'Tim', 'score': 70},
{'name': 'Tam', 'score': 80},
{'name': 'Tem', 'score': 90}
]
I want to get {'name': 'Tem', 'score':90}
but I only can do below: 我想获得{'name': 'Tem', 'score':90}
但我只能在下面做:
max(x['score'] for x in lod)
This only return the value 90
. 这只返回值90
。
How can I get the whole dict? 我怎样才能获得整个字典?
You can use the key function of max
: 你可以使用max
的关键功能 :
>>> lod = [
... {'name': 'Tom', 'score': 60},
... {'name': 'Tim', 'score': 70},
... {'name': 'Tam', 'score': 80},
... {'name': 'Tem', 'score': 90}
... ]
...
>>> max(lod, key=lambda x: x['score'])
{'name': 'Tem', 'score': 90}
Just pass your list to max
, like this: 只需将您的列表传递给max
,如下所示:
>>> from operator import itemgetter
>>> lod = [
... {'name': 'Tom', 'score': 60},
... {'name': 'Tim', 'score': 70},
... {'name': 'Tam', 'score': 80},
... {'name': 'Tem', 'score': 90}
... ]
>>> max(lod, key=itemgetter('score'))
{'score': 90, 'name': 'Tem'}
I dont know whether sorting
is time consuming, 我不知道sorting
是否耗时,
>>>sorted(lod, key=lambda x:x['score'])[-1]
{'name': 'Tem', 'score': 90}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.