PYTHON

Sort Complex Lists of Dictionaries by Multiple Criteria

Discover how to sort a list of dictionaries in Python by multiple custom keys. This enables flexible data ordering for complex datasets, using lambda functions for criteria.

data = [
    {'name': 'Alice', 'age': 30, 'score': 95},
    {'name': 'Bob', 'age': 25, 'score': 88},
    {'name': 'Charlie', 'age': 30, 'score': 92},
    {'name': 'David', 'age': 28, 'score': 95}
]

# Sort primarily by 'age' (ascending), then by 'score' (descending)
sorted_data = sorted(data, key=lambda x: (x['age'], -x['score']))

print("Sorted Data:")
for item in sorted_data:
    print(item)
How it works: This code snippet illustrates how to sort a list of dictionaries based on multiple criteria. The `sorted()` function is used with a `key` argument, which takes a lambda function. The lambda function returns a tuple `(x['age'], -x['score'])`. Python sorts tuples element by element. By making `x['score']` negative, we achieve a descending sort for the score within the same age group, while `age` is sorted in ascending order by default.

Need help integrating this into your project?

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

Hire DigitalCodeLabs