我有一个字典,其中键是字符串,值是整数。
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}
>>> [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()
其他回答
Max ((value, key) for key, value in stats.items())[1]
如果有一个以上的元素,我的值是最大的。我会列出所有值为最大值的键。
>>> 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()
与集合。你可以这样做
>>> 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.
对于科学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'