Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get key with maximum value in Dictionary in Python
A Python dictionary contains key-value pairs. In this article we will see how to get the key of the element whose value is maximum in the given Python dictionary.
Using max() with get()
The max() function with the get() method is the most straightforward approach to find the key with maximum value ?
Example
scores = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:")
print(scores)
# Using max and get
max_key = max(scores, key=scores.get)
print("The Key with max value:")
print(max_key)
The output of the above code is ?
Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue
Using max() with itemgetter()
With itemgetter() function we get the items of the dictionary and by indexing to position 1 we get the values. Then we apply the max() function and extract the key at index 0 ?
Example
import operator
scores = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:")
print(scores)
# Using max and itemgetter
max_key = max(scores.items(), key=operator.itemgetter(1))[0]
print("The Key with max value:")
print(max_key)
The output of the above code is ?
Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue
Using max() with Lambda Function
You can also use a lambda function to extract the value for comparison ?
Example
scores = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:")
print(scores)
# Using max with lambda
max_key = max(scores.items(), key=lambda x: x[1])[0]
print("The Key with max value:")
print(max_key)
The output of the above code is ?
Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue
Comparison
| Method | Imports Needed | Readability | Best For |
|---|---|---|---|
max(dict, key=dict.get) |
None | High | Simple cases |
max(dict.items(), key=itemgetter(1)) |
operator | Medium | Performance-critical code |
max(dict.items(), key=lambda x: x[1]) |
None | Medium | One-time operations |
Conclusion
The max() function with dict.get is the most readable approach for finding the key with maximum value. Use itemgetter() for better performance in loops or large datasets.
