我有一个字典,其中键是字符串,值是整数。
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])
当前回答
例子:
stats = {'a':1000, 'b':3000, 'c': 100}
如果你想用它的键找到Max值,也许下面的步骤很简单,不需要任何相关的函数。
max(stats, key=stats.get)
输出是具有Max值的键。
其他回答
max(stats, key=stats.get)
key, value = max(stats.iteritems(), key=lambda x:x[1])
如果你不关心价值(我会很惊讶,但是),你可以做:
key, _ = max(stats.iteritems(), key=lambda x:x[1])
我更喜欢元组解包,而不是表达式末尾的[0]下标。 我从来都不太喜欢lambda表达式的可读性,但我发现这个比operator.itemgetter(1)更好。
下面是两种简单的方法从给定的字典中提取键的最大值
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总是选择第一个具有Max值的键。字典可以有多个具有该值的键。
def keys_with_top_values(my_dict):
return [key for (key, value) in my_dict.items() if value == max(my_dict.values())]
把这个答案贴出来,希望能帮助到别人。 请看下面的SO帖子
在平局的情况下,Python会选择哪个最大值?
与集合。你可以这样做
>>> 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.