Skip to content
Advertisement

Problems regarding “key” in the min() function

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:

JavaScript

Get’s the key with the minimum value.

Steps:

  1. Iterating through a dictionary directly gives the keys:

    JavaScript
  2. It uses the get method of dictionaries to get the value of that certain key in the dictionary.

    Example:

    JavaScript
  3. The key argument is a function of how you want to compare all the values. Therefore, it 3 since that’s the minimum value in the sequence after processing the function.

    It’s roughly equivalent to:

    JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement