PYTHON
Sort a List of Dictionaries by Key
Learn how to sort a list of Python dictionaries based on the value of a specific key, useful for ordering data from APIs or databases in web development.
users = [
{'name': 'Alice', 'age': 30},
{'name': 'Charlie', 'age': 25},
{'name': 'Bob', 'age': 35}
]
# Sort by 'age' in ascending order
sorted_by_age_asc = sorted(users, key=lambda user: user['age'])
# print(sorted_by_age_asc)
# [{'name': 'Charlie', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 35}]
# Sort by 'name' in descending order
sorted_by_name_desc = sorted(users, key=lambda user: user['name'], reverse=True)
# print(sorted_by_name_desc)
# [{'name': 'Charlie', 'age': 25}, {'name': 'Bob', 'age': 35}, {'name': 'Alice', 'age': 30}]
# In-place sort using .sort()
users.sort(key=lambda user: user['age'])
# print(users) # users list is now sorted by age
How it works: This snippet shows how to sort a list of dictionaries based on the value of a specific key within each dictionary. The `sorted()` built-in function returns a new sorted list, while the `list.sort()` method sorts the list in-place. Both accept a `key` argument, which is a function to be called on each list element prior to making comparisons. A `lambda` function is commonly used here to specify the dictionary key for sorting. The `reverse=True` argument can be used for descending order.