Python
Dictionary
Key-Value Pair
Maximum Value
Programming Tips

Getting key with maximum value in dictionary?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Python, a dictionary is an unordered collection of data in the form of key-value pairs. Being one of the most versatile and widely used data structures, dictionaries offer profound functionalities, including fast lookups, insertions, and deletions. A common requirement when working with dictionaries is to find the key associated with the maximum value. This task can be efficiently performed using basic Python functionalities.

Understanding the Problem

We want to get the key with the maximum value in a dictionary. For example, consider a dictionary that represents the scores of players in a game:

python
1scores = {
2    'Alice': 300,
3    'Bob': 150,
4    'Charlie': 450,
5    'David': 200
6}

Here, Charlie scores the highest with 450 points, and we want to extract 'Charlie' as the key with the maximum value.

Using max() with Dictionaries

The Python max() function can be utilized to achieve this task efficiently. The function can be instructed to compare not directly the keys, but the values or any computed property using a key function. Here is how you can use it:

python
1# Define a dictionary
2scores = {
3    'Alice': 300,
4    'Bob': 150,
5    'Charlie': 450,
6    'David': 200
7}
8
9# Find the key with the maximum value using the max function
10max_key = max(scores, key=scores.get)
11
12print(f"The player with the highest score is {max_key} with {scores[max_key]} points.")

Explanation

  • max(scores, key=scores.get): This finds the key for which the corresponding value is the greatest. The scores.get function is used as the key function, effectively allowing max() to compare values rather than keys.
  • This approach is both simple and efficient with a time complexity of O(n)O(n), where nn is the number of items in the dictionary.

Handling Edge Cases

Empty Dictionary

Attempting to find the maximum value in an empty dictionary will raise a ValueError. You should handle this condition to avoid runtime errors.

python
1scores = {}
2
3if scores:
4    max_key = max(scores, key=scores.get)
5    print(f"The player with the highest score is {max_key} with {scores[max_key]} points.")
6else:
7    print("The dictionary is empty.")

Multiple Maximums

If more than one key shares the maximum value, max() will return the first one it encounters. Here's an example to illustrate this scenario:

python
1scores = {
2    'Alice': 450,
3    'Bob': 150,
4    'Charlie': 450,
5    'David': 200
6}
7
8max_key = max(scores, key=scores.get)
9print(f"The player with the highest score is {max_key} with {scores[max_key]} points.")

In this case, max() will return 'Alice' since Alice and Charlie both have the maximum score of 450, but Alice appears first in the dictionary.

Summary

The table below summarizes the key concepts and techniques described in this article:

Concept/TechniqueDescription
Dictionary in PythonAn unordered collection of key-value pairs with fast data access.
max() functionA built-in function that returns the largest item in an iterable or the largest of two or more arguments.
key parameter in max()Utilizes a key function to determine the value each item in the iterable should be compared by.
Edge Case - Empty DictionaryAn empty dictionary results in a ValueError when passed to max(). Handle this condition beforehand.
Edge Case - Multiple MaximumsIf multiple keys share maximum values, max() returns the first one encountered.

Conclusion

Determining the key with the maximum value in a dictionary is a common task that can be achieved using Python's built-in max() function complemented by the get() method. Though simple, understanding and effectively using these functions while being mindful of potential edge cases, such as empty dictionaries or ties, are paramount for reliable code in complex applications.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.