views:

2788

answers:

5

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?

+16  A: 

You can use operator.itemgetter for that:

import operator
stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]

And instead of building a new list in memory use stats.iteritems(). The key parameter to the max() function is a function that computes a key that is used to determine how to rank items.

unbeknown
Note that this will only work for python2.5 and later, before that max didn't have the key keyword.
Moe
A: 

Thanks, very elegant, I didn't remember that max allows a "key" parameter.

BTW, to get the right answer ('b') it has to be:

import operator
stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
ricafeal
Right, max() returns the key/value pair.
unbeknown
+4  A: 

Here is another one:

stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iterkeys(), key=lambda k: stats[k])

The key-function simply returns the value that should be used for ranking and max() returns the demanded element right away.

unbeknown
.iterkeys is not needed in your answer (it's the default when iterating a dict). However, note that the .iteritems method fetches both key and value in one step, so there is no need for an extra __getitem__ per key as needed with .iterkeys.
ΤΖΩΤΖΙΟΥ
A: 
key,value = max(stats.iteritems(), key=lambda x:x[1])

If you don't care about value (I'd be surprised, but) you can do:

key,ignored = max(stats.iteritems(), key=lambda x:x[1])

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.

Tim Ottinger
`_` could be used instead of `ignored`.
J.F. Sebastian
+8  A: 
max(stats, key=stats.get)
Coady