如果有重复,如何获取字典中最大值的键以及 return 最大数字键
How to get the key of the maxium value in a dictionary and also return the highest number key if there is a duplicate
(抱歉标题模糊)
dic = {1:20, 2:20, 3:20, 4:10}
我希望它是 return 3,因为这是字典中三个重复值之间的最大键号。
我目前拥有的是:
return max(dic, key = dic.get)
但这不会得到我想要的结果,并且 return 1
最大化(值,键)对:
k, _ = max(dic.items(), key=lambda item: item[::-1])
dict项是元组,元组是有序的lexicographically.
替代:
k, _ = sorted(dic.items(), key=lambda x: x[::-1])[-1]
(抱歉标题模糊)
dic = {1:20, 2:20, 3:20, 4:10}
我希望它是 return 3,因为这是字典中三个重复值之间的最大键号。
我目前拥有的是:
return max(dic, key = dic.get)
但这不会得到我想要的结果,并且 return 1
最大化(值,键)对:
k, _ = max(dic.items(), key=lambda item: item[::-1])
dict项是元组,元组是有序的lexicographically.
替代
k, _ = sorted(dic.items(), key=lambda x: x[::-1])[-1]