Getting key with maximum value in dictionary?

2018-12-31 03:01发布

I have a dictionary: keys are strings, values are integers.

Example:

stats = {'a':1000, 'b':3000, 'c': 100}

I'd like to get 'b' as an answer, since it's the key with a higher value.

I did the following, using an intermediate list with reversed key-value tuples:

inverse = [(value, key) for key, value in stats.items()]
print max(inverse)[1]

Is that one the better (or even more elegant) approach?

20条回答
春风洒进眼中
2楼-- · 2018-12-31 03:57
Counter = 0
for word in stats.keys():
    if stats[word]> counter:
        Counter = stats [word]
print Counter
查看更多
ら面具成の殇う
3楼-- · 2018-12-31 03:58

+1 to @Aric Coady's simplest solution.
And also one way to random select one of keys with max value in the dictionary:

stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}

import random
maxV = max(stats.values())
# Choice is one of the keys with max value
choice = random.choice([key for key, value in stats.items() if value == maxV])
查看更多
不流泪的眼
4楼-- · 2018-12-31 03:59

Example:

stats = {'a':1000, 'b':3000, 'c': 100}

if you wanna find the max value with its key, maybe follwing could be simple, without any relevant functions.

max(stats, key=stats.get)

the output is the key which has the max value.

查看更多
梦醉为红颜
5楼-- · 2018-12-31 04:00

To get the maximum key/value of the dictionary stats:

stats = {'a':1000, 'b':3000, 'c': 100}
  • Based on keys

>>> max(stats.items(), key = lambda x: x[0]) ('c', 100)

  • Based on values

>>> max(stats.items(), key = lambda x: x[1]) ('b', 3000)

Of course, if you want to get only the key or value from the result, you can use tuple indexing. For Example, to get the key corresponding to the maximum value:

>>> max(stats.items(), key = lambda x: x[1])[0] 'b'

Explanation

The dictionary method items() in Python 3 returns a view object of the dictionary. When this view object is iterated over, by the max function, it yields the dictionary items as tuples of the form (key, value).

>>> list(stats.items()) [('c', 100), ('b', 3000), ('a', 1000)]

When you use the lambda expression lambda x: x[1], in each iteration, x is one of these tuples (key, value). So, by choosing the right index, you select whether you want to compare by keys or by values.

Python 2

For Python 2.2+ releases, the same code will work. However, it is better to use iteritems() dictionary method instead of items() for performance.

Notes

查看更多
低头抚发
6楼-- · 2018-12-31 04:00

I tested the accepted answer AND @thewolf's fastest solution against a very basic loop and the loop was faster than both:

import time
import operator


d = {"a"+str(i): i for i in range(1000000)}

def t1(dct):
    mx = float("-inf")
    key = None
    for k,v in dct.items():
        if v > mx:
            mx = v
            key = k
    return key

def t2(dct):
    v=list(dct.values())
    k=list(dct.keys())
    return k[v.index(max(v))]

def t3(dct):
    return max(dct.items(),key=operator.itemgetter(1))[0]

start = time.time()
for i in range(25):
    m = t1(d)
end = time.time()
print ("Iterating: "+str(end-start))

start = time.time()
for i in range(25):
    m = t2(d)
end = time.time()
print ("List creating: "+str(end-start))

start = time.time()
for i in range(25):
    m = t3(d)
end = time.time()
print ("Accepted answer: "+str(end-start))

results:

Iterating: 3.8201940059661865
List creating: 6.928712844848633
Accepted answer: 5.464320182800293
查看更多
只若初见
7楼-- · 2018-12-31 04:01

I got here looking for how to return mydict.keys() based on the value of mydict.values(). Instead of just the one key returned, I was looking to return the top x number of values.

This solution is simpler than using the max() function and you can easily change the number of values returned:

stats = {'a':1000, 'b':3000, 'c': 100}

x = sorted(stats, key=(lambda key:stats[key]), reverse=True)
['b', 'a', 'c']

If you want the single highest ranking key, just use the index:

x[0]
['b']

If you want the top two highest ranking keys, just use list slicing:

x[:2]
['b', 'a']
查看更多
登录 后发表回答