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?

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.

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.

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

If using Python3:

```
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
```

Licensed under: CC-BY-SA with attribution

Not affiliated with: Stack Overflow