Daily Python Puzzle: How to Find the Maximum in a Dictionary?

What is the output of this puzzle?

 

# mg per 100g
omega3_table = {
    "Salmon" : 2260,
    "Hering" : 1729,
    "Sardines" : 1480,
    "Flaxseeds" : 53400,
    "Eggs" : 400
    }


y = max(omega3_table, key=lambda x : omega3_table[x])
print(y)

 

In this puzzle, we learn two things.

First, we can retrieve the maximal element of a dictionary using the max function. Recap, a dictionary stores (key, value) pairs. In our example, the keys are strings with the names of five different foods such as ‘Eggs’. The dictionary maps each food name to a numerical value that describes the amount of healthy Omega 3 fats per 100g.

How to find the food (key) in the dictionary containing maximal Omega 3 (value)? To achieve this, we use Python’s built-in max function. But calling max(omega3_table) leads to a strange result. The default max function applied to a dictionary retrieves the maximal key. In the example, this would be the key ‘Sardines’ because it comes last in the alphabet.

To fix this, we specify the key parameter of the max function. The key parameter expects a function that assigns a value to each element in the sequence. This value is then used to determine the maximal value of the sequence. In our example, we use the dictionary value of the respective key. We assign the value omega3_table[x] to each sequence element x.

Second, eat one tablespoon of flaxseeds per day! They are among the healthiest foods on our planet.


Are you a master coder?
Test your skills now!

Related Video

Solution

Flaxseeds

 

Leave a Comment

Your email address will not be published. Required fields are marked *