Python: Sort a List of Dictionaries Using a Lambda — CODEFATHER

Claudio Sabato
5 min readDec 6, 2023

One of Python’s strengths lies in its ability to easily handle complex data structures, like lists of dictionaries. In this article, we will explore a practical application of Python’s lambda functions and sorting capabilities.

In this tutorial, you will learn how lambda functions allow you to sort lists of dictionaries based on specific dictionary keys.

How to Sort a List of Dictionaries with a Lambda

Suppose you have a list of dictionaries where each dictionary represents a person with the following attributes:

  • firstname
  • lastname
  • age

Let’s say you want to sort this list of dictionaries by the age of each person.

Here’s how you can do this using a lambda function in Python:

# Define a list of dictionaries, each representing a person with a firstname, lastname, and age
people = [
{'firstname':'John', 'lastname':'Ross', 'age': 30},
{'firstname':'Mark', 'lastname':'Green', 'age': 25},
{'firstname':'Jane', 'lastname':'Black', 'age': 43}
]

# Sort the list by the 'age' of each person using a lambda function
sorted_people = sorted(people, key=lambda person: person['age'])

# Print the original list
print("Original list:", people)

# Print the sorted list
print("Sorted by age:", sorted_people)

This is the output of the code snippet above:

Original list: [{'firstname': 'John', 'lastname': 'Ross', 'age': 30}, {'firstname': 'Mark', 'lastname': 'Green', 'age': 25}, {'firstname': 'Jane', 'lastname': 'Black', 'age': 43}]
Sorted by age: [{'firstname': 'Mark', 'lastname': 'Green', 'age': 25}, {'firstname': 'John', 'lastname': 'Ross', 'age': 30}, {'firstname': 'Jane', 'lastname': 'Black', 'age': 43}]

You can see that the dictionaries in the list have been correctly sorted based on the age attribute.

Let’s go through the most important lines of this Python code:

  1. sorted(people, key=lambda person: person['age']): This line sorts the list people. The sorted() function returns a new sorted list. The key argument is a lambda function lambda person: person['age']

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.