Custom sort by multiple derived keys

Python data engineering interview problem. Difficulty: intermediate. Pattern: Sorting. About 15 minutes. Part of the Pro drill bank.

HR exports employee rows that must sort by several derived keys (department, then seniority band, then name) rather than by a single column.

An employee report needs a fixed order: group by department, show the longest-serving people first inside each department, and sort by name when everything else is equal. Sort employees by dept (A to Z), then by tenure (largest first), then by name (A to Z). Return a new list. Write sort_employees(rows). For b (eng, tenure 2), a (eng, tenure 2) and c (ops, tenure 9), the order is a, b (both eng, same tenure, so by name), then c (ops). The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Sort by department ascending.
  • Inside a department, sort by tenure descending.
  • Break remaining ties by name ascending.
  • Return a new list.

Constraints

  • Each row is a dictionary with name, dept and tenure.
  • tenure is a number.

Examples

Input: sort_employees([{'name': 'b', 'dept': 'eng', 'tenure': 2}, {'name': 'a', 'dept': 'eng', 'tenure': 2}, {'name': 'c', 'dept': 'ops', 'tenure': 9}]) Output: [{'name': 'a', 'dept': 'eng', 'tenure': 2}, {'name': 'b', 'dept': 'eng', 'tenure': 2}, {'name': 'c', 'dept': 'ops', 'tenure': 9}] This input follows the stated rules and produces this output.

Topics: lakebench, python, sorting.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Custom sort by multiple derived keys

Interview-style drill: Sort a list of employee records by department, then descending tenure, then name.

Sort employees by the multiple derived keys described in the prompt.