使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP