DEV Community

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

4 3

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs