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?
Per the iterated solutions via comments in the selected answer...
In Python 3:
In Python 2:
How about:
Here is another one:
The function
key
simply returns the value that should be used for ranking andmax()
returns the demanded element right away.Given that more than one entry my have the max value. I would make a list of the keys that have the max value as their value.
This will give you 'b' and any other max key as well.
Note: For python 3 use
stats.items()
instead ofstats.iteritems()
You can use
operator.itemgetter
for that:And instead of building a new list in memory use
stats.iteritems()
. Thekey
parameter to themax()
function is a function that computes a key that is used to determine how to rank items.Please note that if you were to have another key-value pair 'd': 3000 that this method will only return one of the two even though they both have the maximum value.
If using Python3: