How to sort a list of dictionaries by a value of the dictionary in Python?

To sort a list of dictionaries by a specific key in Python, use the sorted() function or the list.sort() method with a custom key parameter. Here’s how to do it in various scenarios:

1. Basic Sorting by a Single Key

list_of_dicts = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35}
]

# Sort by 'age' in ascending order
sorted_list = sorted(list_of_dicts, key=lambda x: x["age"])

Result:

[
    {'name': 'Bob', 'age': 25},
    {'name': 'Alice', 'age': 30},
    {'name': 'Charlie', 'age': 35}
]

2. Sort in Descending Order

Add reverse=True:

sorted_list = sorted(list_of_dicts, key=lambda x: x["age"], reverse=True)

Result:

[
    {'name': 'Charlie', 'age': 35},
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25}
]

3. Case-Insensitive Sorting (for Strings)

Use str.lower() to normalize case:

list_of_dicts = [
    {"name": "alice", "grade": "A"},
    {"name": "Bob", "grade": "C"},
    {"name": "Charlie", "grade": "B"}
]

sorted_list = sorted(list_of_dicts, key=lambda x: x["name"].lower())

Result:

[
    {'name': 'alice', 'grade': 'A'},
    {'name': 'Bob', 'grade': 'C'},
    {'name': 'Charlie', 'grade': 'B'}
]

4. Sort by Multiple Keys

Sort by grade first, then name:

sorted_list = sorted(
    list_of_dicts,
    key=lambda x: (x["grade"], x["name"].lower())
)

Result (sorted by grade, then name):

[
    {'name': 'alice', 'grade': 'A'},
    {'name': 'Charlie', 'grade': 'B'},
    {'name': 'Bob', 'grade': 'C'}
]

5. Using operator.itemgetter (Efficient Alternative)

For better performance with large datasets:

from operator import itemgetter

# Sort by 'age'
sorted_list = sorted(list_of_dicts, key=itemgetter("age"))

# Sort by multiple keys
sorted_list = sorted(list_of_dicts, key=itemgetter("grade", "name"))

6. Handle Missing Keys

Use dict.get() to avoid KeyError for optional fields:

# If some dictionaries might lack the key, provide a default value
sorted_list = sorted(list_of_dicts, key=lambda x: x.get("age", 0))

7. In-Place Sorting with list.sort()

Modify the original list instead of creating a new one:

list_of_dicts.sort(key=lambda x: x["age"])

Key Takeaways

  • sorted() vs. list.sort():
  • sorted() returns a new sorted list (original remains unchanged).
  • list.sort() sorts the list in-place (no return value).
  • Lambda Flexibility: Use lambdas for complex logic (e.g., case folding).
  • Performance: operator.itemgetter is faster than lambda for simple key extraction.
  • Missing Keys: Use dict.get(key, default) to safely handle optional keys.

Example: Sort by Nested Dictionary Values

If your dictionaries contain nested data:

users = [
    {"id": 1, "profile": {"name": "Alice", "score": 90}},
    {"id": 2, "profile": {"name": "Bob", "score": 85}},
    {"id": 3, "profile": {"name": "Charlie", "score": 95}}
]

# Sort by nested 'score'
sorted_users = sorted(users, key=lambda x: x["profile"]["score"], reverse=True)

Result:

[
    {'id': 3, 'profile': {'name': 'Charlie', 'score': 95}},
    {'id': 1, 'profile': {'name': 'Alice', 'score': 90}},
    {'id': 2, 'profile': {'name': 'Bob', 'score': 85}}
]

This approach works for any level of nested data!

Leave a Reply

Your email address will not be published. Required fields are marked *