我有一个字典,其中键是字符串,值是整数。
stats = {'a': 1, 'b': 3000, 'c': 0}
如何获得具有最大值的键?在这种情况下,它是'b'。
有没有比使用带有反向键值元组的中间列表更好的方法?
inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
我有一个字典,其中键是字符串,值是整数。
stats = {'a': 1, 'b': 3000, 'c': 0}
如何获得具有最大值的键?在这种情况下,它是'b'。
有没有比使用带有反向键值元组的中间列表更好的方法?
inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
当前回答
+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])
其他回答
与集合。你可以这样做
>>> import collections
>>> stats = {'a':1000, 'b':3000, 'c': 100}
>>> stats = collections.Counter(stats)
>>> stats.most_common(1)
[('b', 3000)]
如果合适,可以从一个空集合开始。计数并加进去
>>> stats = collections.Counter()
>>> stats['a'] += 1
:
etc.
如果有一个以上的元素,我的值是最大的。我会列出所有值为最大值的键。
>>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}
>>> [key for m in [max(stats.values())] for key,val in stats.iteritems() if val == m]
['b', 'd']
这将给你'b'和任何其他最大键。
注意:对于python 3使用stats.items()而不是stats.iteritems()
例子:
stats = {'a':1000, 'b':3000, 'c': 100}
如果你想用它的键找到Max值,也许下面的步骤很简单,不需要任何相关的函数。
max(stats, key=stats.get)
输出是具有Max值的键。
下面是两种简单的方法从给定的字典中提取键的最大值
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表达式的解决方案似乎对较小的输入执行得更好。
在stats为空的情况下,可以在找到value key之前检查一个条件,
stats = {'a':1000, 'b':3000, 'c': 100}
max_key = None
if bool(stats):
max_key = max(stats, key=stats.get)
print(max_key)
这可以首先检查字典是否为空,然后处理。
>>> b