我有一个字典,其中键是字符串,值是整数。
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])
当前回答
Max ((value, key) for key, value in stats.items())[1]
其他回答
key, value = max(stats.iteritems(), key=lambda x:x[1])
如果你不关心价值(我会很惊讶,但是),你可以做:
key, _ = max(stats.iteritems(), key=lambda x:x[1])
我更喜欢元组解包,而不是表达式末尾的[0]下标。 我从来都不太喜欢lambda表达式的可读性,但我发现这个比operator.itemgetter(1)更好。
在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
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')
Counter = 0
for word in stats.keys():
if stats[word]> counter:
Counter = stats [word]
print Counter
你可以使用:
max(d, key=d.get)
# which is equivalent to
max(d, key=lambda k: d.get(k))
要返回键值对,使用:
max(d.items(), key=lambda k: k[1])