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.
Given a dictionary, find all the keys that have minimal value in the dictionary.
We are given a dictionary that has students’ names as the key and their ages as the value.
{"john":12,"steve":20,"robert":19, "diana":15,"riya":12}
[john,riya]
Only john
and riya
are age 12
, which is the minimum value in the given dictionary.
To solve this problem, we will:
for-in
loop and list comprehension.#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)
In the code snippet above:
students
.min
function and pass all values of the dictionary as a parameter to get the minimum value in the dictionary.students
and 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.