How to sort a list of dictionaries by a specific key in Python?

You can use the sorted() function in combination with the key argument to sort a list of dictionaries by a specific key. Here is an example:

# List of dictionaries data = [ {'name': 'John', 'age': 25}, {'name': 'Sarah', 'age': 20}, {'name': 'Mike', 'age': 30}, ] # Sort the list by the 'age' key in ascending order sorted_data = sorted(data, key=lambda x: x['age']) # Print the sorted list for item in sorted_data: print(item)

Output:

{'name': 'Sarah', 'age': 20} {'name': 'John', 'age': 25} {'name': 'Mike', 'age': 30}

In this example, the key argument in the sorted() function is set to lambda x: x['age'], which specifies that the sorting should be based on the value of the 'age' key in each dictionary. The resulting list, sorted_data, will contain the dictionaries sorted by the 'age' key in ascending order.