How do you sort a list of dictionaries by a specific key in Python, and what is the difference between sorted() and list.sort()?
Use sorted() with a key= lambda to produce a new sorted list, or list.sort() to sort in place. Both use Timsort and run in O(n log n). sorted() works on any iterable and returns a new list; list.sort() operates in place and returns None.
How to think about it
What the interviewer is really checking
This question tests whether you know Python’s sorting API well enough to avoid common bugs — especially the list.sort() returns None trap — and whether you can reach for operator.itemgetter instead of always defaulting to a lambda.
The core approach
The mental model is simple: key= is a transform function. Python calls it once per element, sorts the transformed values, and uses those to order the originals. You never touch the comparison logic yourself.
Single-key sort
from operator import itemgetter
employees = [
{"name": "Alice", "salary": 95000},
{"name": "Bob", "salary": 82000},
{"name": "Carol", "salary": 110000},
]
# sorted() — returns a NEW list, original is untouched
by_salary = sorted(employees, key=itemgetter("salary"))
# list.sort() — mutates in place, returns None
employees.sort(key=itemgetter("salary"))
operator.itemgetter is faster than a lambda because it’s implemented in C — no Python function-call overhead per element. For simple key access, prefer it.
Multi-key sort
# Sort by department ascending, then salary descending
data = sorted(
employees,
key=lambda e: (e.get("dept", ""), -e["salary"])
)
Negating a numeric field is the idiomatic way to flip one key to descending without a second pass. Python’s sort is stable: equal keys preserve the original relative order, which is essential when chaining multi-column sorts.
Try it yourself
The key insight
sorted() and .sort() both use Timsort — O(n log n) worst case, O(n) on already-sorted data. The only difference is whether you want the original list preserved. When in doubt, use sorted() because it’s safer and works on any iterable, not just lists.