Find Key with Max Value in Dictionary in Python: Simple Guide
Use the
max() function with a key argument to find the dictionary key that has the highest value. For example, max(your_dict, key=your_dict.get) returns the key with the maximum value.Syntax
The syntax to find the key with the maximum value in a dictionary is:
max(dictionary, key=dictionary.get)
Here, dictionary is your dictionary variable.
The max() function finds the maximum element based on the function given in key. Using dictionary.get tells it to compare dictionary values.
python
max_key = max(dictionary, key=dictionary.get)Example
This example shows how to find the key with the highest value in a dictionary of fruits and their quantities.
python
fruits = {'apple': 10, 'banana': 25, 'orange': 15}
max_fruit = max(fruits, key=fruits.get)
print(max_fruit)Output
banana
Common Pitfalls
One common mistake is trying to use max() without the key argument, which returns the maximum key alphabetically, not by value.
Another mistake is using max(dictionary.values()) which returns the maximum value but not the key.
python
fruits = {'apple': 10, 'banana': 25, 'orange': 15}
# Wrong: returns max key alphabetically
wrong_key = max(fruits)
print(wrong_key) # Output: orange
# Wrong: returns max value only
max_value = max(fruits.values())
print(max_value) # Output: 25
# Right: returns key with max value
max_key = max(fruits, key=fruits.get)
print(max_key) # Output: bananaOutput
orange
25
banana
Quick Reference
- max(dictionary, key=dictionary.get): Returns key with highest value.
- dictionary.get: Function to get value for each key.
- Use
min(dictionary, key=dictionary.get)to find key with smallest value.
Key Takeaways
Use max(dictionary, key=dictionary.get) to find the key with the highest value.
Without the key argument, max() returns the maximum key alphabetically, not by value.
max(dictionary.values()) returns the maximum value, not the key.
You can use min(dictionary, key=dictionary.get) to find the key with the smallest value.