我想从字典列表中返回具有最高值的字典。所以因为' key1'这里包含5,我只想回到那本词典,因为它是我唯一关心的词典。我需要来自不同键的值,但是在具有最高值的字典中。应该很容易,但我错过了一些东西。谢谢!
例如:
[{'key1': 1, 'key2': 'string'},
{'key1': 3, 'key2': 'string'},
{'key1': 5, 'key2': 'string with highest value'},
]
我需要得到的是字典' {' key1':5,' key2':'字符串具有最高价值'}&# 39;
答案 0 :(得分:3)
max(L, key=operator.itemgetter('key1'))
答案 1 :(得分:0)
您可以编写for循环来检查列表中的每个项目:
data = [
{'key1': 1, 'key2': 'string'},
{'key1': 3, 'key2': 'string'},
{'key1': 5, 'key2': 'string with highest value'},
]
highest = None
result = None
for item in data:
value_key1 = item['key1']
if highest is None or value_key1 > highest:
highest = value_key1
result = item['key2']
print(result)
答案 2 :(得分:0)
您应该订购列表,然后获取第一个 例如:
f = [{'key1': 1, 'key2': 'string'},
{'key1': 3, 'key2': 'string'},
{'key1': 5, 'key2': 'string with highest value'},
]
order_list = sorted(f,key=lambda x:x["key1"],reverse=True)
first = order_list[0]