Question
How to Sort a List of Dictionaries by Key in Python
Question
How can I sort a list of dictionaries in Python using the value of a specific key?
For example, given this list:
people = [
{"name": "Homer", "age": 39},
{"name": "Bart", "age": 10}
]
If I sort the list by the name key, the result should be:
[
{"name": "Bart", "age": 10},
{"name": "Homer", "age": 39}
]
Short Answer
By the end of this page, you will understand how to sort a list of dictionaries in Python by a specific dictionary key. You will learn when to use sorted() versus list.sort(), how the key argument works, and how to avoid common mistakes such as missing keys or sorting the wrong data type.
Concept
A list of dictionaries is a very common Python data structure. You often use it when working with records such as users, products, orders, or API responses.
To sort this kind of data, Python needs to know what value inside each dictionary should be used for comparison. That is what the key argument is for.
You usually sort with one of these:
sorted(data, key=...)
or:
data.sort(key=...)
The key function is called once for each item in the list. It returns the value Python should use to decide the order.
For a list of dictionaries, that often looks like this:
key=lambda item: item["name"]
This means:
- take each dictionary
- get its
namevalue - sort using that value
This matters in real programming because many datasets are stored as collections of objects or dictionaries. Sorting lets you:
- show users data in a predictable order
- sort tables by columns
- order API results
- prepare reports
- organize logs or records before processing
Mental Model
Think of each dictionary as a folder containing labeled pieces of information.
For example:
- one label is
name - another label is
age
Sorting a list of dictionaries is like saying:
"Put all these folders in order based on the value written on the
namelabel."
Python does not automatically know which label you want. The key argument is you pointing to the correct label.
So this:
key=lambda person: person["name"]
means:
"For each folder, look at the
namelabel and use that to sort."
Syntax and Examples
Basic syntax
Using sorted()
new_list = sorted(old_list, key=lambda item: item["name"])
sorted()returns a new sorted list- the original list stays unchanged
Using list.sort()
old_list.sort(key=lambda item: item["name"])
list.sort()changes the original list in place- it does not create a new list
Example: sort by name
people = [
{"name": "Homer", "age": 39},
{"name": "Bart", "age": 10}
]
sorted_people = sorted(people, key=lambda person: person["name"])
print(sorted_people)
Output:
Step by Step Execution
Consider this example:
people = [
{"name": "Homer", "age": 39},
{"name": "Bart", "age": 10}
]
result = sorted(people, key=lambda person: person["name"])
print(result)
Here is what happens step by step:
- Python reads the
peoplelist. sorted()starts processing each dictionary in the list.- For the first dictionary:
the key function returns:{"name": "Homer", "age": 39}"Homer" - For the second dictionary:
the key function returns:{"name": "Bart", "age": 10}"Bart" - Python compares the key values:
Real World Use Cases
Sorting a list of dictionaries appears in many practical tasks.
API responses
You might fetch users from an API and sort them by username or signup date.
users = [
{"username": "zoe", "id": 3},
{"username": "alex", "id": 1}
]
users = sorted(users, key=lambda user: user["username"])
Product lists
An online store may sort products by price, rating, or name.
products = [
{"name": "Keyboard", "price": 50},
{"name": "Mouse", "price": 25}
]
products.sort(key=lambda product: product["price"])
Reports and dashboards
You may sort employee records by department, salary, or last name before displaying them.
Log or event processing
Events stored as dictionaries are often sorted by timestamp.
events = [
{"event": "logout", : },
{: , : }
]
ordered_events = (events, key= event: event[])
Real Codebase Usage
In real projects, developers often use sorting together with validation, formatting, and filtering.
Common pattern: sort before display
visible_users = [user for user in users if user["active"]]
visible_users.sort(key=lambda user: user["name"])
This filters first, then sorts the remaining records.
Common pattern: guard against missing keys
If some dictionaries may not contain the same key, developers often use .get().
people = [
{"name": "Homer", "age": 39},
{"age": 10}
]
sorted_people = sorted(people, key=lambda person: person.get("name", ""))
Common pattern: sort by multiple fields
people = [
{"name": "Homer", "age": 39},
{"name": "Homer", "age": 40},
{"name": "Bart", : }
]
sorted_people = (people, key= person: (person[], person[]))
Common Mistakes
1. Forgetting the key argument
Broken code:
people = [
{"name": "Homer", "age": 39},
{"name": "Bart", "age": 10}
]
sorted(people)
Why it fails:
- Python cannot directly compare dictionaries to decide their order
Fix:
sorted(people, key=lambda person: person["name"])
2. Expecting list.sort() to return the sorted list
Broken code:
people = [
{"name": "Homer", "age": 39},
{"name": "Bart", "age": 10}
]
result = people.sort(key=lambda person: person["name"])
print(result)
Problem:
- returns
Comparisons
Sorting options in Python
| Approach | Changes original list? | Returns a new list? | Best when |
|---|---|---|---|
sorted(data, key=...) | No | Yes | You want to keep the original data unchanged |
data.sort(key=...) | Yes | No | You want to sort the existing list in place |
lambda vs itemgetter
| Approach | Example | Best when |
|---|---|---|
lambda | key=lambda x: x["name"] |
Cheat Sheet
# Sort by one key, return new list
sorted_people = sorted(people, key=lambda person: person["name"])
# Sort in place
people.sort(key=lambda person: person["name"])
# Sort descending
sorted_people = sorted(people, key=lambda person: person["age"], reverse=True)
# Sort by multiple keys
sorted_people = sorted(people, key=lambda person: (person["name"], person["age"]))
# Handle missing keys safely
sorted_people = sorted(people, key=lambda person: person.get("name", ""))
# Case-insensitive sort
sorted_people = sorted(people, key=lambda person: person["name"].lower())
Quick rules:
- Use
sorted()when you want a new list - Use
.sort()when you want to modify the existing list - Use
key=to tell Python what value to compare - Use
reverse=Truefor descending order - Use
.get()if keys may be missing
FAQ
How do I sort a list of dictionaries by key in Python?
Use sorted() or .sort() with a key function:
sorted(people, key=lambda person: person["name"])
What is the difference between sorted() and sort() in Python?
sorted() returns a new sorted list. .sort() modifies the original list and returns None.
How do I sort a list of dictionaries in descending order?
Use reverse=True:
sorted(people, key=lambda person: person["age"], reverse=True)
How do I sort when some dictionaries are missing the key?
Use .get() with a default value:
sorted(people, key= person: person.get(, ))
Mini Project
Description
Build a small Python script that manages a list of student records stored as dictionaries. You will sort the records by different fields such as name and score. This mirrors common tasks in real applications, such as ordering API data, leaderboard entries, or admin dashboard tables.
Goal
Create a program that sorts a list of student dictionaries by name and by score, including descending order for leaderboard-style output.
Requirements
- Create a list containing at least four student dictionaries with
nameandscorekeys. - Print the original list.
- Print a new list sorted by
namein ascending order. - Print a new list sorted by
scorein descending order. - Keep the original list unchanged when creating sorted results.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.