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?
Thanks, very elegant, I didn't remember that max allows a "key" parameter.
BTW, to get the right answer ('b') it has to be:
A heap queue is a generalised solution which allows you to extract the top n keys ordered by value:
Note
dict.__getitem__
is the method called by the syntactic sugardict[]
. As opposed todict.get
, it will returnKeyError
if a key is not found, which here cannot occur.