How to Sort Dictionaries in Python?

What is the output of this puzzle?


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

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


In this puzzle, we show how to sort a dictionary not after the keys but after the values. 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 sort the foods (keys) in the dictionary with respect to how much Omega 3 they contain (value)? To achieve this, we use Python’s built-in sorted function. Yet, calling sorted(omega3_table) leads to a strange result. When applying the default sorted function to a dictionary, sorting is done with respect to the keys, not the values.

To fix this, we specify the key parameter of the sorted function. The key parameter expects a function that assigns a value to each element in the sequence. This value is then used to sort 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.

Python by default sorts in an ascending order. Hence, the last element of the sorted sequence (with maximal Omega 3) is the food ‘Flaxseeds’. Takeaway: 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




Leave a Comment