5 Best Ways to Sort a List of Dictionaries Alphabetically in Python

πŸ’‘ Problem Formulation: When working with lists of dictionaries in Python, it’s common to need them sorted by the values of a specific key. For instance, if you have a list of employee records, where each record is a dictionary with details like ‘name’, ‘age’, and ‘position’, you might want to sort them alphabetically by the ‘name’ key. The desired output is a list of dictionaries but ordered such that the values pertaining to the ‘name’ key follow an alphabetical sequence.

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

This method involves the built-in sorted() function, which returns a new sorted list. By specifying a lambda function as the key argument, we can tell sorted() how to compare items. In this case, the lambda function accesses the value associated with a given key, making the sort order based on the values of that key.

Here’s an example:

employees = [
    {'name': 'John', 'age': 45, 'position': 'manager'},
    {'name': 'Alice', 'age': 30, 'position': 'assistant'},
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}
]

sorted_employees = sorted(employees, key=lambda x: x['name'])
print(sorted_employees)

Output:

[
    {'name': 'Alice', 'age': 30, 'position': 'assistant'}, 
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}, 
    {'name': 'John', 'age': 45, 'position': 'manager'}
]

The sorted() function takes our list of dictionaries and sorts them alphabetically by the values associated with the ‘name’ key, resulting in a list where the dictionaries are ordered from ‘Alice’ to ‘John’.

Method 2: Using the itemgetter() Function from operator Module

The operator module’s itemgetter() function can be used as a high-performance, more readable alternative to a lambda function. It generates a function that extracts the value of a specified key, which can then be used as the key for sorted().

Here’s an example:

from operator import itemgetter

employees = [
    {'name': 'John', 'age': 45, 'position': 'manager'},
    {'name': 'Alice', 'age': 30, 'position': 'assistant'},
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}
]

sorted_employees = sorted(employees, key=itemgetter('name'))
print(sorted_employees)

Output:

[
    {'name': 'Alice', 'age': 30, 'position': 'assistant'}, 
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}, 
    {'name': 'John', 'age': 45, 'position': 'manager'}
]

By using itemgetter('name'), we achieve the same result as the lambda function, sorting the list of dictionaries alphabetically based on the ‘name’ key.

Method 3: In-Place Sorting with list.sort()

When you want to sort a list in-place, without creating a new list, you can use the list.sort() method with a key function. This is similar to using sorted(), but this method modifies the list it’s called on.

Here’s an example:

employees = [
    {'name': 'John', 'age': 45, 'position': 'manager'},
    {'name': 'Alice', 'age': 30, 'position': 'assistant'},
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}
]

employees.sort(key=lambda x: x['name'])
print(employees)

Output:

[
    {'name': 'Alice', 'age': 30, 'position': 'assistant'}, 
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}, 
    {'name': 'John', 'age': 45, 'position': 'manager'}
]

The .sort() method changes the original employees list to be sorted alphabetically by the ‘name’ key.

Method 4: Sorting with Custom Comparator Function

For more complex sorting that might involve multiple conditions or customized comparison logic, one can define a custom comparator function and use it with the sorted() function by setting it as the key argument.

Here’s an example:

def sort_by_name(employee):
    return employee['name'].lower()  # Case-insensitive sorting

employees = [
    {'name': 'john', 'age': 45, 'position': 'manager'},
    {'name': 'Alice', 'age': 30, 'position': 'assistant'},
    {'name': 'bob', 'age': 25, 'position': 'trainee'}
]

sorted_employees = sorted(employees, key=sort_by_name)
print(sorted_employees)

Output:

[
    {'name': 'Alice', 'age': 30, 'position': 'assistant'}, 
    {'name': 'bob', 'age': 25, 'position': 'trainee'}, 
    {'name': 'john', 'age': 45, 'position': 'manager'}
]

This custom sort_by_name function allows for case-insensitive alphabetical sorting of the list based on the ‘name’ key.

Bonus One-Liner Method 5: Sorting Using List Comprehension and Tuples

With list comprehension and tuple unpacking, you can perform a sort by generating a sorted list of keys and then mapping the original list to match this new order. This succinct method is best for simple sorting cases.

Here’s an example:

employees = [
    {'name': 'John', 'age': 45, 'position': 'manager'},
    {'name': 'Alice', 'age': 30, 'position': 'assistant'},
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}
]

sorted_names = sorted([e['name'] for e in employees])
sorted_employees = [next(e for e in employees if e['name'] == name) for name in sorted_names]
print(sorted_employees)

Output:

[
    {'name': 'Alice', 'age': 30, 'position': 'assistant'}, 
    {'name': 'Bob', 'age': 25, 'position': 'trainee'}, 
    {'name': 'John', 'age': 45, 'position': 'manager'}
]

This method first creates a sorted list of ‘name’ keys and then rebuilds the original list of dictionaries according to that order. It’s a clever one-liner but less efficient for larger datasets due to its O(n^2) complexity.

Summary/Discussion

  • Method 1: Using sorted() with a Lambda. Strength: Easy to understand. Weakness: May be slower for large datasets or complex lambda functions.
  • Method 2: Using itemgetter(). Strength: Clean and potentially faster than lambdas. Weakness: Less flexible than lambda.
  • Method 3: In-Place Sorting using list.sort(). Strength: Modifies the list in-place, saving memory. Weakness: List is modified directly, which may not be desired.
  • Method 4: Sorting with Custom Comparator Function. Strength: Highly customizable and can be made case-insensitive. Weakness: Extra code to write and maintain.
  • Method 5: List Comprehension and Tuples. Strength: Elegant one-liner. Weakness: Inefficient for larger lists.