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.py131 chars6 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.py165 chars6 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