我有一个字典,其中键是字符串,值是整数。
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])
当前回答
与集合。你可以这样做
>>> 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, 'e':3000}
你可以得到一个包含所有最大值键的集合,如下所示:
from collections import defaultdict
from collections import OrderedDict
groupedByValue = defaultdict(list)
for key, value in sorted(stats.items()):
groupedByValue[value].append(key)
# {1000: ['a'], 3000: ['b', 'd', 'e'], 100: ['c']}
groupedByValue[max(groupedByValue)]
# ['b', 'd', 'e']
下面是两种简单的方法从给定的字典中提取键的最大值
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表达式的解决方案似乎对较小的输入执行得更好。
更容易理解的方法:
mydict = { 'a':302, 'e':53, 'g':302, 'h':100 }
max_value_keys = [key for key in mydict.keys() if mydict[key] == max(mydict.values())]
print(max_value_keys) # prints a list of keys with max value
输出:['a', 'g']
现在你只能选择一个键:
maximum = mydict[max_value_keys[0]]
试试这个:
sorted(dict_name, key=dict_name.__getitem__, reverse=True)[0]
Counter = 0
for word in stats.keys():
if stats[word]> counter:
Counter = stats [word]
print Counter