Python Program to Find the Key with the Maximum Value in a Dictionary
Beginner · Dictionaries
This program finds which key has the largest value in a dictionary, such as the student with the highest mark. It goes through every pair and remembers the best one seen so far.
Program
Scores: {'Riya': 88, 'Arjun': 72, 'Meera': 95, 'Kabir': 64}
Highest score: Meera with 95How it works
best_nameandbest_scorestart asNone, which means nothing has been seen yet.- The loop looks at every (name, score) pair, and the first pair, or any pair with a higher score, becomes the new best.
- Starting from
Noneinstead of 0 means the program still works when every value is negative. - Because the test is
>, a later key with the same top value does not replace the first one.
Other ways to write it
Using max() with key
Highest: Meera 95 Lowest: Kabir 64
max() goes through the keys, and key=scores.get makes it compare them by their values. This is the shortest and most common way.
All the keys that share the top value
Highest score: 95 Scored by: ['Riya', 'Meera']
max() on its own would name only one of the tied students, so this finds the top value first and then collects every key that has it.
Try it yourself
Change the program to find the key with the smallest value by flipping > to <.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Sort a Dictionary by Value
- Find the Sum of All Values in a Dictionary
- Find the Largest and Smallest Number in a List
- Find Students Who Scored Above 75 Using a Dictionary
- Merge Two Dictionaries
- Sort a Dictionary by Key
- Check if a Key Exists in a Dictionary
- Create a Dictionary from Two Lists
- Remove a Key from a Dictionary
All Python programs · CBSE class 12 practical file · Python exercises