簡體   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