DEV Community 👩‍💻👨‍💻

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

Python Exercise 9: find the key with the minimum value in a dictionary

Question

  • Get the key of a minimum value from the following dictionary
sample_dict = {
  'Physics': 82,
  'Math': 65,
  'history': 75
}
Enter fullscreen mode Exit fullscreen mode

Hint

  • use build-in min() function

My attempt

  • search and read the min(), though it is easy, but cannot figure out the answer

Recommend solution

sample_dict = {
    'Physics': 82,
    'Math': 65,
    'history': 75
}
print(min(sample_dict, key=sample_dict.get))
Enter fullscreen mode Exit fullscreen mode

What the min() function here does is ,

  • it call the simple_dict.get() method on each key of the sample_dict
    • i.e. sample_dict.get(Physics),simple_dict.get(Math),simple_dict.get(history) will be called
    • a list of values of the sample_dict will be return
  • and then use the values for comparison
  • at last, the min() function will return corresponding key for the lowest value.

    key point

  • do not add () parentheses after the key=sample_dict.get
  • as the min() function will execute the method for you, you just need to pass it the method name, not to execute it.

My reflection

  • From this exercise, i learn there is more about the min() function, and understand why sometimes () parentheses is not added after method name or function name.

Credit

Top comments (0)

🌚 Life is too short to browse without dark mode