How To Sort A List of Python Dictionaries

Part 2 of a series on sorting Python lists

Binge On Code
Python in Plain English

--

How to sort python list — part two

This is the second part of this awesome short series of how to sort a Python list. We will be sorting a list of Python dictionaries! So let’s do this!

Well, the first part of this mini-series introduced you to some of the core concepts of how to sort Python lists. This second part will expound on that, by going a step further, with a little bit complex example.

If you recall, the last sort Python list mini-series worked with a simple list of numbers. BUT it was important since it got to introduce you to the very basics of how to go about with your Python sorting. If you haven’t checked it out, please do so, because it will help you understand some of the concepts here.

So, just like the previous example, we will have this in two parts, defining our data and then the next part will cover how to sort Python list of Python dictionary.

Defining data

In this example, we will have a Python dictionary list of hypothetical contents per 1kg of different foods servings.

For this, our Python dictionary will look like so:

"""
{
'name': {string},
'calories_in_cals_per_kg': {number},
'proteins_in_grams_per_kg': {number}
}
"""

As you can see, it is really straightforward.

The name is just the name of the serving, calories_in_cals_per_kg refers to how many calories we can get from 1 kg of that food serving, and proteins_in_grams_per_kg is the protein amount per 1kg serving.

Of course, you can add other hypothetical attributes and values as well.

Declaring our data

Now that we know the structure of the data we are going to work with to sort Python dictionary list, let’s declare our data:

foods = [
{
'name': 'Maize Flour',
'calories_in_cals_per_kg': 88,
'proteins_in_grams_per_kg': 43
},
{
'name': 'Rice',
'calories_in_cals_per_kg': 105,
'proteins_in_grams_per_kg': 55
},
{
'name': 'Yams',
'calories_in_cals_per_kg': 97,
'proteins_in_grams_per_kg': 87
},
{
'name': 'Beans',
'calories_in_cals_per_kg': 50,
'proteins_in_grams_per_kg': 111
}
]

Okay, now that the data is ready, let’s begin learning how to sort Python dictionary list.

Requirements

Since we are going to be using only Python methods, we will be using the famous itemgetter from operator module.

So, we import it:

from operator import itemgetter

Now we are ready to use itemgetter.

How to use itemgetter with Python sorted

Now that we have imported itemgetter into our script, we introduce it to Python sorted method like so:

sorted(list_to_sort, key=itemgetter('attribute_to_use'))

This is the default of how to use Python sorted to sort Python dictionary list. Notice that we are passing in the attribute_to_use as a key into the Python sorted method.

So, let’s try and sort our foods based on the calories:

sort_foods_based_on_calories = sorted(foods, key=itemgetter('calories_in_cals_per_kg'))
print(sort_foods_based_on_calories)

What this will do is that it will sort Python list of dictionaries which we pass into it, and by DEFAULT it will sort in ascending order, BASED on the specified attribute.

Okay, now, let’s change the challenge and say we want to instead sort the Python list provided, from one with the highest calories to the lowest calories.

sort_foods_based_on_highest_calories = sorted(foods, key=itemgetter('calories_in_cals_per_kg'), reverse=True)
print(sort_foods_based_on_highest_calories)

Well, notice the reverse parameter, if you don’t know what it does, simply find the link at the bottom for the previous article which introduces how to sort a Python list.

Okay, so, if you want to have the list sorted by the highest proteins per kg, then our Python sorted method will be like so:

sort_foods_based_on_highest_proteins = sorted(foods, key=itemgetter('proteins_in_grams_per_kg'), reverse=True)
print(sort_foods_based_on_highest_proteins)

Well, it is that simple!

Okay, what if you try to sort by an attribute which is not there? Well, you will receive Python KeyError showing you the missing attribute you are trying to sort by.

Some key concepts

Okay, as you can see, it is not that difficult to sort a Python list of dictionaries. So, just like the previous article, we have a couple of key concepts you should take from this tutorial.

  • You will need itemgetter from the operator module.
  • Python sorted method will accept a key attribute that you want to sort by. This points to the value returned by itemgetter.

Conclusion

Well, that is it from this article.

If some of the concepts introduced here, such as how to use Python sorted to sort Python list, are unclear, simply find the full introduction in the previous article.

Happy Coding!

Are you interested in learning Python? Checkout similar awesome articles here: Related Articles

More content at plainenglish.io

--

--

You love programming? Well, we do! We are a team of one as of now and are really passionate about programming and making the world better today than yesterday!