Skip to main content
 首页 » 编程设计

python之如何比较python列表中的两个字典

2025年05月04日20qq78292959

我在迭代 python 列表中的字典值时遇到问题。

例如:

list1 = [{'id': 1, 'score': 2}, {'id': 2, 'score': 1}] 

我想比较两个词典的分数并获取id 最高分的

谢谢

请您参考如下方法:

您可以将内置的 max 函数与您定义的键函数一起使用:

list1 = [{'id': 1, 'score': 2}, {'id': 2, 'score': 1}] 
 
result = max(list1, key = lambda x : x['score'])['id'] 
 
print(result) 

输出:

1