Skip to content

Q&A · Answered

How to sort a list of dictionaries in Python

asked 9 months, 1 week ago 1562 views 1 answer
30

I have a list of dictionaries and want to sort by a specific key.

1 Answer

One accepted
25

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
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'))

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.