W3docs

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 can use the built-in max() function in Python to get the key with the maximum value in a dictionary. Note that calling max() on a dictionary iterates over its keys by default. You pass the dictionary to max() along with a key argument, such as dict.get, which tells max() to compare values instead of keys.

Here is an example:

Getting key with maximum value in dictionary in Python

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.

Alternatively, you can use the max() function with the items() method to retrieve both the key and its corresponding maximum value.

Getting key with maximum value in dictionary in Python using the items function

my_dict = {'a': 1, 'b': 2, 'c': 3}
max_item = max(my_dict.items(), key=lambda x: x[1])
print(max_item)

This will output ('c', 3).

Keep in mind that max() will raise a KeyError if called on an empty dictionary. Always verify that the dictionary is non-empty before calling max().