PYTHON

Custom Sorting for Lists of Dictionaries in Python

Discover how to sort a list of dictionaries or custom objects in Python using the `key` argument with `sorted()` and `list.sort()` for flexible sorting.

data = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 24, 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': 35, 'city': 'Chicago'},
    {'name': 'David', 'age': 24, 'city': 'Houston'}
]

# Sort by 'age' in ascending order
sorted_by_age = sorted(data, key=lambda person: person['age'])
print("
Sorted by age (asc):")
for item in sorted_by_age:
    print(item)

# Sort by 'age' in descending order
sorted_by_age_desc = sorted(data, key=lambda person: person['age'], reverse=True)
print("
Sorted by age (desc):")
for item in sorted_by_age_desc:
    print(item)

# Sort by 'age' then by 'name' (secondary sort key)
sorted_by_age_name = sorted(data, key=lambda person: (person['age'], person['name']))
print("
Sorted by age then name:")
for item in sorted_by_age_name:
    print(item)

# In-place sort using list.sort() (modifies the original list)
data.sort(key=lambda person: person['city'])
print("
Sorted in-place by city:")
for item in data:
    print(item)
How it works: Python's `sorted()` function and `list.sort()` method allow custom sorting using the `key` argument. This argument accepts a function that is called on each element of the list to extract a comparison key. For lists of dictionaries, a `lambda` function is commonly used to specify which dictionary key(s) to sort by. You can sort by multiple keys by returning a tuple from the `key` function, where the sorting order follows the tuple elements. `sorted()` returns a new sorted list, while `list.sort()` sorts the list in place.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs