How to get minimum value keys from a dictionary in Python
In this shot, we will learn how to get the keys with the minimum value in a dictionary.
We will start by defining the problem statement followed by an example.
Problem statement
Given a dictionary, find all the keys that have minimal value in the dictionary.
Example
We are given a dictionary that has students’ names as the key and their ages as the value.
Input
{"john":12,"steve":20,"robert":19, "diana":15,"riya":12}
Output
[john,riya]
Explanation
Only john and riya are age 12, which is the minimum value in the given dictionary.
Implementation
To solve this problem, we will:
- Get all values from a dictionary.
- Find out the minimum value from them.
- Traverse through the dictionary using the
for-inloop and list comprehension. - Check if the present key value equals the minimum value. If it does, we add it to the list.
- Finally, print the list.
#declare dictionary studentsstudents = {"john":12,"steve":20,"robert":19, "diana":15,"riya":12}#find minimum value in dictionaryminimum_value = min(students.values())#get keys with minimal value using list comprehensionminimum_keys = [key for key in students if students[key]==minimum_value]#print the minimum keysprint(minimum_keys)
Explanation
In the code snippet above:
- Line 2: We declare and initialize the dictionary
students. - Line 7: We use the
minfunction and pass all values of the dictionary as a parameter to get the minimum value in the dictionary. - Line 10: We traverse through the dictionary
studentsand check if the present key’s value is equal to the minimum value. If it is, we use list comprehension to add it to a list. - Line 13: We print the list of keys that have a minimum value in the dictionary.