Monnil Roy
Monnil Roy

Reputation: 1

Finding out key for minimum value of dictionary

scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598}

Scores is a dict I have defined and now I want to find out the key, for the minimum value in the dictionary, which should return me 100.

I notice that it can be done like this

min(scores, key=scores.get)

But I don't really understand what the above line means. I am new to python programming. Can anyone break this line down for me visually? Any help would be appreciated.

Upvotes: 0

Views: 367

Answers (2)

dizzy77
dizzy77

Reputation: 543

Maybe more simply: When you call min(scores), you are returning the item in scores that has the lowest value among all items in scores.

When you call min(scores, key=some_func), you are returning the item in scores that has the lowest value of some_func(item), instead.

For example, if scores is a list of (unique) integers, then min(scores) will return the lowest integer. If some_func(x) returns the negative of x, then min(scores, key=some_func) will return the maximum, instead.

Upvotes: 0

Jab
Jab

Reputation: 27485

From the docs provided by Patrick

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.

So basically using scores.get as the key function calls scores.get(key) for each key in scores.

When passing scores as the data to min it treats it basically as a list of the keys so essentially it’s finding the minimum value and returning you the associated key.

Upvotes: 1

Related Questions