Sort List of Dictionaries in Python (2 Examples)
In this post you’ll learn how to sort a list of dictionaries in the Python programming language.
The tutorial will contain the following content blocks:
Let’s take a look at some Python codes in action!
Example Data and Importing Modules
For one of the examples, we need to utilize the operator module. You can import it as follows.
from operator import itemgetter # importing itemgetter from operator module
As a next step, we’ll also need to create some example data, which is a list of dictionaries.
room_list = [{"room_no":315, "type":"A", "price":80}, # creating example list {"room_no":100, "type":"B", "price":80}, {"room_no":210, "type":"C", "price":35}]
Example 1: Sort List of Dictionaries in Python by Lambda Expression
Example 1 demonstrates how to use a lambda expression to sort a list of dictionaries. In this case, it is used for specifying the reference field, which is “price” in this case, in sorting.
price_sorted = sorted(room_list, key=lambda d: d['price']) # creating a sorted list print(price_sorted) # printing sorted list # [{'room_no': 210, 'type': 'C', 'price': 35}, # {'room_no': 315, 'type': 'A', 'price': 80}, # {'room_no': 100, 'type': 'B', 'price': 80}]
Example 2: Sort List of Dictionaries in Python by itemgetter() Function
Example 2 illustrates how to use the itemgetter() function, which essentially does the same thing as the code in Example 1. However, it is part of the operator module, and it can sort our list with respect to multiple fields.
room_no_sorted = sorted(room_list, key=itemgetter('price','room_no')) # creating a sorted list print(room_no_sorted) # printing sorted list # [{'room_no': 210, 'type': 'C', 'price': 35}, # {'room_no': 100, 'type': 'B', 'price': 80}, # {'room_no': 315, 'type': 'A', 'price': 80}]
Video, Further Resources & Summary
Would you like to know more about the sorting of a list of dictionaries? Then I recommend having a look at the following video on my YouTube channel. I’m demonstrating the Python codes of this tutorial in the video.
The YouTube video will be added soon.
Additionally, you could have a look at the other tutorials at https://www.statisticsglobe.com/:
- Sort List of datetime Objects in Python
- Sort pandas DataFrame by Date in Python
- Access Dictionary within List in Python
- Check if Value Exists in List of Dictionaries in Python
- Introduction to Python Programming
In this Python programming tutorial, you have learned how to create a sorted list of dictionaries in Python. Please tell me about it in the comments if you have further questions.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.
Statistics Globe Newsletter