Skip to content

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:

  1. salary, highest first. A None salary goes after everyone with a salary.
  2. then dept, A to Z
  3. 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 1sorted(rows, key=...) with a tuple key sorts by the first element, then the second, and so on.
Hint 2To sort one numeric part high to low and the rest low to high, negate the number instead of using reverse=True.
Hint 3Comparing None with an int raises TypeError. Put salary is None first in the key: False sorts before True.

Learn the concepts

More Python problems

All Python problems