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.py226 chars11 lines
This will output:
main.py139 chars7 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