30
I have a list of dictionaries and want to sort by a specific key.
Loading...
Q&A · Answered
I have a list of dictionaries and want to sort by a specific key.
Accepted answer
users = [
{'name': 'John', 'age': 30},
{'name': 'Jane', 'age': 25},
{'name': 'Bob', 'age': 35}
]
# Sort by age
sorted_users = sorted(users, key=lambda x: x['age'])
# Sort descending
sorted_users = sorted(users, key=lambda x: x['age'], reverse=True)
# Sort in place
users.sort(key=lambda x: x['name'])
# Using operator
from operator import itemgetter
sorted_users = sorted(users, key=itemgetter('age'))Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.