How to Sort a List of Dictionaries by a Key in Python

students = [
    {'name': 'Alice', 'score': 85},
    {'name': 'Bob', 'score': 92},
    {'name': 'Charlie', 'score': 78}
sorted_students = sorted(students, key=lambda x: x['score'], reverse=True)
print(f"Original List of Dictionaries: {students}\nSorted List by Score: {sorted_students}")


Original List of Dictionaries: [{‘name’: ‘Alice’, ‘score’: 85}, {‘name’: ‘Bob’, ‘score’: 92}, {‘name’: ‘Charlie’, ‘score’: 78}]
Sorted List by Score: [{‘name’: ‘Bob’, ‘score’: 92}, {‘name’: ‘Alice’, ‘score’: 85}, {‘name’: ‘Charlie’, ‘score’: 78}]

Leave a Comment

Your email address will not be published.