Find Key with Minimum Value in Dictionary in Python
Use the
min() function with the dictionary and specify key=dictionary.get to find the key with the smallest value. For example, min_key = min(my_dict, key=my_dict.get) returns the key that has the minimum value.Syntax
The syntax to find the key with the minimum value in a dictionary is:
min_key = min(dictionary, key=dictionary.get)
Here, dictionary is your dictionary variable.
The min() function finds the smallest item based on the function provided by key=. Using dictionary.get tells it to compare dictionary values.
python
min_key = min(dictionary, key=dictionary.get)Example
This example shows how to find the key with the smallest value in a dictionary of fruits and their prices.
python
fruits = {'apple': 5, 'banana': 2, 'cherry': 7, 'date': 3}
min_key = min(fruits, key=fruits.get)
print(min_key)Output
banana
Common Pitfalls
One common mistake is trying to use min() directly on dictionary values without specifying the key function, which returns the smallest key alphabetically, not by value.
Another mistake is using min(dictionary.values()) which returns the smallest value but not the key.
Always use min(dictionary, key=dictionary.get) to get the key with the minimum value.
python
fruits = {'apple': 5, 'banana': 2, 'cherry': 7, 'date': 3}
# Wrong: returns smallest key alphabetically
wrong_key = min(fruits)
print(wrong_key) # Output: apple
# Wrong: returns smallest value only
min_value = min(fruits.values())
print(min_value) # Output: 2
# Right: returns key with smallest value
min_key = min(fruits, key=fruits.get)
print(min_key) # Output: bananaOutput
apple
2
banana
Quick Reference
- min(dictionary, key=dictionary.get): Returns key with smallest value
- max(dictionary, key=dictionary.get): Returns key with largest value
- Use
dictionary.getto compare values, not keys
Key Takeaways
Use min(dictionary, key=dictionary.get) to find the key with the smallest value.
Do not use min(dictionary) alone, it returns the smallest key alphabetically.
min(dictionary.values()) returns the smallest value, not the key.
Always specify key=dictionary.get to compare dictionary values.
This method works efficiently for any dictionary with comparable values.