使用 Python 獲取具有最大值的字典中的鍵


一個 Python 字典包含鍵值對。在本文中,我們將瞭解如何獲取在給定的 Python 字典中其值為最大值的元素的鍵。

使用 max 和 get

我們使用 get 函式和 max 函式來獲取鍵。

示例

 線上演示

dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:\n",dictA)
# Using max and get
MaxKey = max(dictA, key=dictA.get)
print("The Key with max value:\n",MaxKey)

輸出

執行以上程式碼會給出我們以下結果 −

Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue

使用 itemgetter 和 max

藉助 itemgetter 函式,我們獲取字典中各元素並透過將其編入位置一來獲取值。接下來我們使用 max 函式,最終我們獲取所需鍵。

示例

 線上演示

import operator
dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:\n",dictA)
# Using max and get
MaxKey = max(dictA.items(), key = operator.itemgetter(1))[0]
print("The Key with max value:\n",MaxKey)

輸出

執行以上程式碼會給出我們以下結果 −

Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue

更新日期: 04-06-2020

694 瀏覽

啟動您的 職業生涯

完成課程以獲得認證

開始
廣告