# 5 Best Ways to Sort a List of Dictionaries by Key in Python

π‘ Problem Formulation:

Often in Python programming, you encounter a list of dictionaries and the need arises to sort this list by a specific key. Consider an input like this:

`[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 22}, {"name": "Charlie", "age": 30}]`
The goal is to sort these dictionaries by the key “age”, in ascending order, resulting in an output like so:
`[{"name": "Bob", "age": 22}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 30}]`

## Method 1: Using the `sorted()` Function with a Lambda

The `sorted()` function can be used in Python to sort a list. When dealing with a list of dictionaries, a lambda function can serve as the key argument to sort the dictionaries by a specified key.

Here’s an example:

```people = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 22}, {"name": "Charlie", "age": 30}]
sorted_people = sorted(people, key=lambda x: x['age'])```

Output:

`[{"name": "Bob", "age": 22}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 30}]`

This code snippet sorts the list of dictionaries based on the value associated with the ‘age’ key. The `lambda` function extracts the ‘age’ value for each dictionary, which the `sorted()` function uses as the basis for the sorting order.

## Method 2: Using the `sorted()` Function with the `itemgetter()`

The `itemgetter()` function from the `operator` module allows a more efficient and faster sort by specifying the dictionary key. This can be especially beneficial when sorting by multiple keys.

Here’s an example:

```from operator import itemgetter
people = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 22}, {"name": "Charlie", "age": 30}]
sorted_people = sorted(people, key=itemgetter('age'))```

Output:

`[{"name": "Bob", "age": 22}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 30}]`

Here, the `itemgetter('age')` function is creating a callable that extracts the ‘age’ key from each dictionary, which is then passed to the `sorted()` function as the key function for sorting the list.

## Method 3: Using List Comprehension and Assigning the Sorted Values Back

This method involves generating a list of sorted tuples by the key of interest and then using list comprehension to build a new list of dictionaries. While this method is not commonly recommended, it serves well when there is a need for transformation or filtering in the process.

Here’s an example:

```people = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 22}, {"name": "Charlie", "age": 30}]
sorted_tuples = sorted((person['age'], person) for person in people)
sorted_people = [person for age, person in sorted_tuples]```

Output:

`[{"name": "Bob", "age": 22}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 30}]`

This approach works by first creating a sorted list of tuples, then reconstructing the list of dictionaries. This effectively sorts the dictionaries by the ‘age’ key while keeping the rest of the dictionary intact.

## Method 4: In-Place Sorting Using the `list.sort()` Method

The `list.sort()` method sorts a list in place, rather than returning a new list. This method is helpful when it is acceptable to modify the original list, and it has the advantage of not requiring additional memory for another sorted list.

Here’s an example:

```people = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 22}, {"name": "Charlie", "age": 30}]
people.sort(key=lambda x: x['age'])```

Output:

`[{"name": "Bob", "age": 22}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 30}]`

Similar to Method 1, the `lambda` function extracts the ‘age’ value for the sorting criteria. The `sort()` method applies the sorting in-place without creating a new list.

## Bonus One-Liner Method 5: Using List Comprehension with `sorted()` and `itemgetter()`

Combining a one-liner list comprehension with `sorted()` and `itemgetter()` can provide a succinct way to sort a list of dictionaries by a key.

Here’s an example:

```from operator import itemgetter
people = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 22}, {"name": "Charlie", "age": 30}]
sorted_people = [dict(t) for t in sorted((person.items(), person) for person in people, key=itemgetter(0))]```

Output:

`[{"name": "Bob", "age": 22}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 30}]`

This code combines a tuple construct containing the dictionary items and the dictionary itself within a comprehension and sorts by the first element of the tuple, which is the result of calling `items()` on each dictionary and is used as the key for sorting.

## Summary/Discussion

• Method 1: Using `sorted()` Function with a Lambda. Strengths: Simple and easy to read. Weaknesses: Could be slower than `itemgetter()` for large datasets.
• Method 2: Using `sorted()` with `itemgetter()`. Strengths: Fast and efficient, especially for sorting on multiple keys. Weaknesses: Requires importing a module.
• Method 3: Using List Comprehension and Assigning Sorted Values Back. Strengths: Offers flexibility for transformation. Weaknesses: Less straightforward and potentially less readable.
• Method 4: In-Place Sorting Using the `list.sort()` Method. Strengths: Modifies the list in place, saving memory. Weaknesses: Original list order is lost.
• Bonus Method 5: One-Liner List Comprehension. Strengths: Succinct code. Weaknesses: Readability may suffer for those not used to the syntax.