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?
+1 to @Aric Coady's simplest solution.
And also one way to random select one of keys with max value in the dictionary:
Example:
if you wanna find the max value with its key, maybe follwing could be simple, without any relevant functions.
the output is the key which has the max value.
To get the maximum key/value of the dictionary
stats
:>>> max(stats.items(), key = lambda x: x[0]) ('c', 100)
>>> 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 themax
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
expressionlambda 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 ofitems()
for performance.Notes
This answer is based on the comments on Climbs_lika_Spyder's answer.
The used code was tested on Python 3.5.2 and Python 2.7.10 .
I tested the accepted answer AND @thewolf's fastest solution against a very basic loop and the loop was faster than both:
results:
I got here looking for how to return
mydict.keys()
based on the value ofmydict.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:If you want the single highest ranking key, just use the index:
If you want the top two highest ranking keys, just use list slicing: