[英]How to select the dictionary with the highest value in Python?
我有几个具有相同键的字典的列表,我想 select 具有特定键的最高值的字典。 值是数字,我该怎么做?
例如,当特定键a
我想 select stats[0]
时,因为 1000 大于 10。
stats = [{'a':1000, 'b':3000, 'c': 100}, {'a':10, 'b':200, 'c': 1}]
将max
与选择a
的key
function 一起使用:
max(stats, key=lambda d: d['a'])
您可以使用这个 function:
def select_max (dict, key):
max = dict[0][key]
maxElement = dict[0]
for element in dict:
if element[key] > max:
maxElement = element
max = element[key]
return maxElement
输入:
select_max([{'a':1000, 'b':3000, 'c': 100}, {'a':10, 'b':200, 'c': 1}],'a')
Output:
{'a': 1000, 'b': 3000, 'c': 100}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.