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?
I have tested MANY variants, and this is the fastest way to return the key of dict with the max value:
To give you an idea, here are some candidate methods:
The test dictionary:
And the test results under Python 3.2:
And under Python 2.7:
You can see that
f1
is the fastest under Python 3.2 and 2.7 (or, more completely,keywithmaxval
at the top of this post)max((value, key) for key, value in stats.items())[1]
If you don't care about value (I'd be surprised, but) you can do:
I like the tuple unpacking better than a [0] subscript at the end of the expression. I never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.
With
collections.Counter
you could doIf appropriate, you could simply start with an empty
collections.Counter
and add to itIf you need to know only a key with the max value you can do it without
iterkeys
oriteritems
because iteration through dictionary in Python is iteration through it's keys.EDIT:
From comments, @user1274878 :
Yep...
max
The optional
key
argument describes how to compare elements to get maximum among them:Returned values will be compared.
Dict
Python dict is a hash table. A key of dict is a hash of an object declared as a key. Due to performance reasons iteration though a dict implemented as iteration through it's keys.
Therefore we can use it to rid operation of obtaining a keys list.
Closure
The
stats
variable available through__closure__
attribute of thelambda
function as a pointer to the value of the variable defined in the parent scope.