11. Sort by Several Keys
Difficulty: Medium · Topic: Core Python & data structures
Write rank_employees(rows). Each row is a dict with name, dept and salary. Return the names ordered by:
salary, highest first. ANonesalary goes after everyone with a salary.- then
dept, A to Z - then
name, A to Z
Your code runs in CPython on our servers against 4 tests, including hidden ones.
Sample test
rank_employees([
{'name': 'Asha', 'dept': 'eng', 'salary': 90},
{'name': 'Ben', 'dept': 'sales', 'salary': 120},
{'name': 'Chitra', 'dept': 'eng', 'salary': 120},
{'name': 'Dev', 'dept': 'eng', 'salary': None},
])Expected: ['Chitra', 'Ben', 'Asha', 'Dev']
Hints
Hint 1
sorted(rows, key=...) with a tuple key sorts by the first element, then the second, and so on.Hint 2
To sort one numeric part high to low and the rest low to high, negate the number instead of usingreverse=True.Hint 3
ComparingNone with an int raises TypeError. Put salary is None first in the key: False sorts before True.Learn the concepts
- Sorting with key functions · 5 min read. Tuple keys, mixed directions, stability and data with None in it.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium