简体   繁体   English

如何在一个dicts列表中获得具有公共密钥最大值的整个dict

[英]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.

相关问题 如何将具有公共键值对的字典列表转换为以键为公共值的新字典? - How do i convert the list of dicts having common key value pair to a new dict with keys as the common value? 如何从字典列表中的字典中获取值 - How to get a value from a dict in a list of dicts 如何计算字典列表中特定字典键的出现次数,一些字典值包含列表和 append 计数值 - How to count occurrences of a specific dict key in dicts list and some dicts values ​contains list and append the count in value 每个dict键具有值的dicts列表中的最大值和最小值 - Max and min value in list of dicts where each dict key has a value 如何在字典的字典中找到具有最高值的键? - how to find the key with the highest value in a dict of dicts? 替换字典或嵌套字典或字典列表中键值的泛型函数 - Generic Function to replace value of a key in a dict or nested dict or list of dicts 在 List of Dicts 中,找到常用 Dict 字段的 min() 值 - In List of Dicts, find min() value of a common Dict field 如何从字典列表中通过字典值y获取字典值x - How to get dict value x via dict value y from list of dicts 如何在字典或字典的字典中查找字符串是键还是值 - How to find whether a string either a key or a value in a dict or in a dict of dicts 获取字典列表的最大值索引 - Get max value index for a list of dicts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM