Editor

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

key_with_max_value.py
scores = {"Riya": 88, "Arjun": 72, "Meera": 95, "Kabir": 64}
best_name = None
best_score = None
for name, score in scores.items():
if best_score is None or score > best_score:
best_name = name
best_score = score
print("Scores:", scores)
print("Highest score:", best_name, "with", best_score)
Output
Scores: {'Riya': 88, 'Arjun': 72, 'Meera': 95, 'Kabir': 64}
Highest score: Meera with 95

How it works

  1. best_name and best_score start as None, which means nothing has been seen yet.
  2. The loop looks at every (name, score) pair, and the first pair, or any pair with a higher score, becomes the new best.
  3. Starting from None instead of 0 means the program still works when every value is negative.
  4. 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

Using max() with key
scores = {"Riya": 88, "Arjun": 72, "Meera": 95, "Kabir": 64}
top = max(scores, key=scores.get)
bottom = min(scores, key=scores.get)
print("Highest:", top, scores[top])
print("Lowest:", bottom, scores[bottom])
Output
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

All the keys that share the top value
scores = {"Riya": 95, "Arjun": 72, "Meera": 95, "Kabir": 64}
highest = max(scores.values())
toppers = [name for name, score in scores.items() if score == highest]
print("Highest score:", highest)
print("Scored by:", toppers)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises