In this tutorial, we will look at how to get the key with the maximum value in a Python dictionary with the help of some examples.
How to get the key with the max value in a dictionary?

You can use the Python built-in max()
function to get the key with the maximum value in a dictionary. Pass the dictionary’s get function as an argument to the key
parameter. The following is the syntax:
# key with highest value in the dictionary max(sample_dict, key=sample_dict.get)
It returns the key which has the largest value in the dictionary.
Let’s look at an example.
We have a dictionary containing the salaries of the different employees in a company. You want to find the employee with the highest salary.
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
# create a dictionary salary = { "Michael": 90000, "Jim": 75000, "Dwight": 80000 } # get key with maximum value print(max(salary, key=salary.get))
Output:
Michael
Here we find the key in the dictionary salary
which has the maximum value. We find that “Michael” has the largest salary.
What would happen if there are more than one key with the maximum value? In that case, the max()
function would return the first key it encounters having the maximum value.
To get all the keys with max value in a dictionary, you can use a list comprehension.
# create a dictionary salary = { "Michael": 90000, "Jim": 75000, "Dwight": 80000, "Ryan": 90000 } # get key with maximum value print([key for key in salary.keys() if salary[key]==max(salary.values())])
Output:
['Michael', 'Ryan']
We get all the employees with the maximum salary.
Using a loop
Alternatively, you can iterate through the dictionary items in a loop and keep track of the key with the maximum value.
Let’s use the same use-case as above. Finding the maximum salary in the dictionary of names to salaries.
# create a dictionary salary = { "Michael": 90000, "Jim": 75000, "Dwight": 80000 } # get key with maximum value max_val = None max_val_key = None for key, val in salary.items(): if max_val is None: max_val = val max_val_key = key if val > max_val: max_val = val max_key = key print(max_val_key)
Output:
Michael
We get the same result as above. “Michael” has the highest salary in the given dictionary. Using a loop may not be the best solution here. Other methods mentioned above are also straightforward and they require fewer lines of code.
You might also be interested in –
- Get Value for a Key in a Python Dictionary
- Count Occurrences of a Value in a Python Dictionary
- Check If a Python Dictionary Contains a Specific Key
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.