Question

How to Sort a List of Dictionaries by Key in Python

pythonlistsortingdictionarydata-structures

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 name value
  • 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 name label."

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 name label and use that to sort."

Take Quiz

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:

[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

Example: sort by age

people = [
    {"name": "Homer", "age": 39},
    {"name": "Bart", "age": 10}
]

sorted_people = sorted(people, key=lambda person: person["age"])

print(sorted_people)

Output:

[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

Example: descending order

Use reverse=True when you want largest-to-smallest or Z-to-A order.

people = [
    {"name": "Homer", "age": 39},
    {"name": "Bart", "age": 10}
]

sorted_people = sorted(people, key=lambda person: person["age"], reverse=True)

print(sorted_people)

Output:

[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

Cleaner alternative with itemgetter

Python also provides itemgetter from the operator module.

from operator import itemgetter

people = [
    {"name": "Homer", "age": 39},
    {"name": "Bart", "age": 10}
]

sorted_people = sorted(people, key=itemgetter("name"))
print(sorted_people)

This does the same thing and is often used in real codebases.

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:

  1. Python reads the people list.
  2. sorted() starts processing each dictionary in the list.
  3. For the first dictionary:
    {"name": "Homer", "age": 39}
    
    the key function returns:
    "Homer"
    
  4. For the second dictionary:
    {"name": "Bart", "age": 10}
    
    the key function returns:
    "Bart"
    
  5. Python compares the key values:
    • "Bart"
    • "Homer"
  6. Alphabetically, "Bart" comes before "Homer".
  7. Python builds a new list in that order.
  8. result becomes:
[
    {"name": "Bart", "age": 10},
    {"name": "Homer", "age": 39}
]

A useful thing to notice: Python sorts the whole dictionaries, not just the names. The names are only used to decide the order.

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", "time": 1700},
    {"event": "login", "time": 900}
]

ordered_events = sorted(events, key=lambda event: event["time"])
Take Quiz

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", "age": 10}
]

sorted_people = sorted(people, key=lambda person: (person["name"], person["age"]))

This sorts by name first, then age when names are equal.

Common pattern: case-insensitive sorting

people = [
    {"name": "homer", "age": 39},
    {"name": "Bart", "age": 10}
]

sorted_people = sorted(people, key=lambda person: person["name"].lower())

This prevents uppercase and lowercase differences from producing unexpected order.

Common pattern: keep original data unchanged

In larger codebases, sorted() is often preferred when you do not want to mutate shared data.

sorted_config = sorted(config_items, key=lambda item: item["priority"])

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:

  • list.sort() returns None

Fix:

people.sort(key=lambda person: person["name"])
print(people)

Or use:

result = sorted(people, key=lambda person: person["name"])
print(result)

3. Using a key that does not exist

Broken code:

sorted(people, key=lambda person: person["first_name"])

Problem:

  • raises KeyError if first_name is missing

Fix:

sorted(people, key=lambda person: person.get("first_name", ""))

4. Mixing incompatible value types

Problem example:

people = [
    {"name": "Homer", "age": 39},
    {"name": "Bart", "age": "10"}
]

sorted(people, key=lambda person: person["age"])

Why it can fail:

  • one age is an integer and one is a string
  • Python cannot reliably compare them

Fix:

  • keep data types consistent
sorted(people, key=lambda person: int(person["age"]))

5. Forgetting about uppercase and lowercase order

people = [
    {"name": "homer"},
    {"name": "Bart"}
]

Default sorting may give surprising results because uppercase letters are handled differently.

Fix:

sorted(people, key=lambda person: person["name"].lower())

Comparisons

Sorting options in Python

ApproachChanges original list?Returns a new list?Best when
sorted(data, key=...)NoYesYou want to keep the original data unchanged
data.sort(key=...)YesNoYou want to sort the existing list in place

lambda vs itemgetter

ApproachExampleBest when
lambdakey=lambda x: x["name"]You want something easy to read and flexible
itemgetterkey=itemgetter("name")You want a concise built-in helper

Single-key vs multi-key sorting

TypeExampleUse when
Single keykey=lambda x: x["name"]One field decides the order
Multiple keyskey=lambda x: (x["name"], x["age"])You need tie-breaking with extra fields

Ascending vs descending

OrderExample
Ascendingsorted(data, key=lambda x: x["age"])
Descendingsorted(data, key=lambda x: x["age"], reverse=True)
Take Quiz

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=True for descending order
  • Use .get() if keys may be missing
  • Keep compared values the same type when possible

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=lambda person: person.get("name", ""))

Can I sort by more than one dictionary key?

Yes. Return a tuple from the key function:

sorted(people, key=lambda person: (person["name"], person["age"]))

Why does sorted(my_list_of_dicts) fail?

It usually fails because Python cannot compare dictionaries directly without being told which value to use.

Is lambda required for sorting dictionaries?

No. You can also use itemgetter:

from operator import itemgetter
sorted(people, key=itemgetter("name"))
Take Quiz

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 name and score keys.
  • Print the original list.
  • Print a new list sorted by name in ascending order.
  • Print a new list sorted by score in descending order.
  • Keep the original list unchanged when creating sorted results.
Take Quiz

Keep learning

Related questions

View more