我有一个字典,其中键是字符串,值是整数。
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, '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']
其他回答
只是添加一个你想要选择某些键而不是所有键的情况:
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])```
d = {'A': 4,'B':10}
min_v = min(zip(d.values(), d.keys()))
# min_v is (4,'A')
max_v = max(zip(d.values(), d.keys()))
# max_v is (10,'B')
对于科学python用户,这里有一个使用Pandas的简单解决方案:
import pandas as pd
pd.Series({'a': 1000, 'b': 3000, 'c': 100}).idxmax()
>>> b
你可以使用运算符。Itemgetter:
import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
并且使用stats.iteritems()而不是在内存中构建一个新的列表。max()函数的key参数是一个函数,它计算一个用于确定如何对项目排序的键。
请注意,如果你有另一个键值对'd': 3000,这个方法将只返回其中一个,即使它们都有最大值。
>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
如果使用Python3:
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
如何:
max(zip(stats.keys(), stats.values()), key=lambda t : t[1])[0]