key with highest values in python

To get the key with the highest value in a Python dictionary, we can sort the dictionary based on the values and then return the key of the first element of the sorted list. Here is an example implementation:

main.py
my_dict = {'a': 3, 'b': 2, 'c': 5, 'd': 1}

key_with_max_val = max(my_dict, key=my_dict.get)
print(key_with_max_val)
# Output: 'c'
131 chars
6 lines

Here, max() is the built-in python function that returns the maximum value from a list or an iterable. We use the key parameter to tell Python to sort the dictionary based on its values, and then max() returns the key of the dictionary with the highest value.

Alternatively, we can sort the dictionary items based on values using a lambda function to extract the second element of each tuple, which is the dictionary value, and then return the first element, which is the key:

main.py
my_dict = {'a': 3, 'b': 2, 'c': 5, 'd': 1}

key_with_max_val = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)[0][0]
print(key_with_max_val)
# Output: 'c'
165 chars
6 lines

Here, we use the sorted() function to sort the dictionary items based on their second element, which is the value, in descending order (reverse=True). The lambda function specifies the key of the sort, by extracting the value from each tuple using x[1]. Finally, we return the key of the first item of the sorted list, which corresponds to the key with the highest value.

gistlibby LogSnag