I have a dictionary where keys are strings, and values are integers.
stats = {'a': 1, 'b': 3000, 'c': 0}
How do I get the key with the maximum value? In this case, it is 'b'.
Is there a nicer approach than using an intermediate list with reversed key-value tuples?
inverse = [(value, key) for key, value in stats.items()] print(max(inverse)[1])
You can use
operator.itemgetterfor that:And instead of building a new list in memory use
stats.iteritems(). Thekeyparameter 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: