Home > database >  Problems regarding "key" in the min() function
Problems regarding "key" in the min() function

Time:11-10

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?

CodePudding user response:

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
    >>> 
    

CodePudding user response:

key (optional) - key function where the iterables are passed and comparison is performed based on its return value

You'd need to perform an operation in key which is like giving a function that returns a value.

Quoted from

CodePudding user response:

What's happening is the key argument takes a function. That function gets called for each key in your dictionary, and the value that function returns is used to find the "min" value.

In your case, calling scores.get(3) would return 0, which is less than any of the other results, which is why 3 is, indeed, your result.

Supplying "scores.get()" as the key raises an error because "get" requires at least 1 argument (the value that you are "getting"). Passing just scores for key gives the error that the dictionary is not callable because you are passing a dictionary rather than a callable function.

  • Related