繁体   English   中英

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

[英]How to compare two dictionaries in a python list?

我在遍历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

您可以只使用max()和key属性来指示您要比较分数:

from operator import itemgetter
list1 = [{'id': 1, 'score': 2}, {'id': 2, 'score': 1}]

item = max(list1, key=itemgetter('score') )
# item is: {'id': 1, 'score': 2}
item['id']

结果:

1
list1 = [{'id': 1, 'score': 2}, {'id': 2, 'score': 1}]
list1.sort(key=lambda x:x['score'],reverse=True)

sol = list1[0]['id']
print(sol)

# output 1
>>> list1 = [{'fruit': 'apple', 'calories': 137}, {'fruit': 'banana', 'calories': 254}, {'fruit': 'orange', 'calories': 488}]
>>> list1
[{'fruit': 'apple', 'calories': 137}, {'fruit': 'banana', 'calories': 254}, {'fruit': 'orange', 'calories': 488}]
>>> for dictionary in list1:
    print(dictionary)

{'fruit': 'apple', 'calories': 137}
{'fruit': 'banana', 'calories': 254}
{'fruit': 'orange', 'calories': 488}
>>> dictionary1 = list1[0]
>>> dictionary1
{'fruit': 'apple', 'calories': 137}
>>> for key in dictionary1:
    print(key)

fruit
calories
>>> for value in dictionary1.values():
    print(value)


apple
137
>>> for items in dictionary.items():
    print(items)


('fruit', 'orange')
('calories', 488)

这样可以清除一切吗?

尝试这个:

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

输出:

1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM