Getting key with maximum value in dictionary?
You can use the built-in max()
function in Python to get the key with the maximum value in a dictionary. You would pass in the dictionary to the max()
function, along with the key function as an argument, which is a lambda function that returns the value of the key-value pair.
Here is an example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
max_key = max(my_dict, key=my_dict.get)
print(max_key)
This will output 'c'
, which is the key associated with the maximum value in the dictionary.
Watch a video course
Python - The Practical Guide
Alternatively, you can use the sorted()
function and the items()
function to get the max key and value
my_dict = {'a': 1, 'b': 2, 'c': 3}
max_key = max(my_dict, key=my_dict.get)
print(max(my_dict.items(), key = lambda x: x[1]))
This will output ('c', 3)