sort a list of dictionaries in python

To sort a list of dictionaries in Python, we can use the built-in sorted function with a key parameter that specifies a function to extract the value to be used as the sorting key. We can also use a lambda function to accomplish this in a more concise way.

Here is an example code snippet that sorts a list of dictionaries based on the 'age' key in each dictionary:

main.py
people = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 32},
    {'name': 'Charlie', 'age': 18},
    {'name': 'David', 'age': 29}
]

sorted_people = sorted(people, key=lambda p: p['age'])

print(sorted_people)
226 chars
11 lines

This will output:

main.py
[
    {'name': 'Charlie', 'age': 18},
    {'name': 'Alice', 'age': 25},
    {'name': 'David', 'age': 29},
    {'name': 'Bob', 'age': 32}
]
139 chars
7 lines

In this example, we are using a lambda function to extract the 'age' value from each dictionary in the list, and sorting the list based on that value. The resulting sorted list of dictionaries is then assigned to the sorted_people variable and printed to the console.

gistlibby LogSnag