我有一个字典,其中键是字符串,值是整数。

stats = {'a': 1, 'b': 3000, 'c': 0}

如何获得具有最大值的键?在这种情况下,它是'b'。


有没有比使用带有反向键值元组的中间列表更好的方法?

inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])

当前回答

这是另一个:

stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iterkeys(), key=lambda k: stats[k])

函数键只是返回应该用于排序的值,max()立即返回所需的元素。

其他回答

+1到@Aric Coady最简单的解决方案。 还有一种方法是随机选择字典中最大值的键之一:

stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}

import random
maxV = max(stats.values())
# Choice is one of the keys with max value
choice = random.choice([key for key, value in stats.items() if value == maxV])

只是添加一个你想要选择某些键而不是所有键的情况:

stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000, 'e':3000}
keys_to_search = ["a", "b", "c"]

max([k for k in keys_to_search], key=lambda x: stats[x])```
max(stats, key=stats.get, default=None)

如果stats可以是一个空字典,则只使用max(stats, key=stats.get)将引发ValueError。

这个答案是安全的,只要在字典中不是一个可能的键。

下面是两种简单的方法从给定的字典中提取键的最大值

import time
stats = {
   "a" : 1000,
   "b" : 3000,
   "c" : 90,
   "d" : 74,
   "e" : 72,
 }

start_time = time.time_ns()
max_key = max(stats, key = stats.get)
print("Max Key [", max_key, "]Time taken (ns)", time.time_ns() - start_time)

start_time = time.time_ns()
max_key = max(stats, key=lambda key: stats[key])
print("Max Key with Lambda[", max_key, "]Time taken (ns)", time.time_ns() - start_time)

输出

Max Key [ b ] Time taken (ns) 3100
Max Key with Lambda [ b ] Time taken (ns) 1782

使用Lambda表达式的解决方案似乎对较小的输入执行得更好。

你可以使用:

max(d, key=d.get) 
# which is equivalent to 
max(d, key=lambda k: d.get(k))

要返回键值对,使用:

max(d.items(), key=lambda k: k[1])