在Python的Dictionary中获取具有最大值的键

Python字典包含键值对。在本文中,我们将看到如何获取给定Python字典中值最大的元素的键。

随着最大和得到

我们使用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