How to Sort List of Dictionaries by Key in Python
To sort a list of dictionaries by a key in Python, use the
sorted() function with a key argument that extracts the dictionary value by that key, typically using a lambda function. For example, sorted(list_of_dicts, key=lambda x: x['key_name']) sorts the list by the values of 'key_name'.Syntax
The basic syntax to sort a list of dictionaries by a key is:
sorted(list_of_dicts, key=lambda x: x['key_name'])
- list_of_dicts: Your list containing dictionaries.
- key=: A function that tells Python which dictionary value to use for sorting.
- lambda x: x['key_name']: A small function that gets the value of
'key_name'from each dictionary.
python
sorted(list_of_dicts, key=lambda x: x['key_name'])
Example
This example shows how to sort a list of dictionaries by the key 'age' in ascending order.
python
people = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
sorted_people = sorted(people, key=lambda x: x['age'])
print(sorted_people)Output
[{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
Common Pitfalls
Common mistakes include:
- Using
list.sort()without akeyfunction, which won't sort dictionaries by a specific key. - Trying to sort by a key that does not exist in all dictionaries, causing errors.
- Forgetting that
sorted()returns a new list and does not change the original list.
Here is an example of a wrong and right way:
python
# Wrong: This will cause an error if 'age' key is missing people = [{'name': 'Alice'}, {'name': 'Bob', 'age': 25}] # sorted_people = sorted(people, key=lambda x: x['age']) # KeyError # Right: Use dict.get() with a default value to avoid errors sorted_people = sorted(people, key=lambda x: x.get('age', 0)) print(sorted_people)
Output
[{'name': 'Alice'}, {'name': 'Bob', 'age': 25}]
Quick Reference
Tips for sorting lists of dictionaries:
- Use
sorted()for a new sorted list orlist.sort()to sort in place. - Use
key=lambda x: x['key_name']to specify the sorting key. - Add
reverse=Trueto sort in descending order. - Handle missing keys safely with
dict.get().
Key Takeaways
Use sorted(list_of_dicts, key=lambda x: x['key_name']) to sort by a dictionary key.
sorted() returns a new sorted list; list.sort() sorts the list in place.
Handle missing keys safely using dict.get() with a default value.
Add reverse=True to sort in descending order.
Always ensure the key exists or provide a fallback to avoid errors.