scores = {1:20, 2:40, 3:0, 4:25}
min_score = min(scores, key=scores.get)
I don’t quite understand the parameters that can be passed into the key. Running the above code gives me 3 which is what I wanted. scores.get return me a dict object at certain memory address.
Calling scores.get() raised me an Error. key = scores complained that dict object is not callable.
My question why scores cannot be used as arguments into the key?
Advertisement
Answer
The below code:
min(scores, key=scores.get)
Get’s the key with the minimum value.
Steps:
Iterating through a dictionary directly gives the keys:
>>> list(scores) [1, 2, 3, 4] >>>
It uses the
get
method of dictionaries to get the value of that certain key in the dictionary.Example:
>>> scores.get(1) 20 >>> scores.get(2) 40 >>> scores.get(3) 0 >>> scores.get(4) 25 >>>
The
key
argument is a function of how you want to compare all the values. Therefore, it3
since that’s the minimum value in the sequence after processing the function.It’s roughly equivalent to:
>>> min(scores, key=lambda x: scores.get(x)) 3 >>>