使用 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 浏览

启动您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.