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:

min(scores, key=scores.get)

Get’s the key with the minimum value.

Steps:

  1. Iterating through a dictionary directly gives the keys:

    >>> list(scores)
    [1, 2, 3, 4]
    >>> 
    
  2. 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
    >>> 
    
  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:

    >>> min(scores, key=lambda x: scores.get(x))
    3
    >>> 
    
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement