L2 · Working engineerPython internals~3 min · 3 tests#70

Sort a List of Dictionaries by Key

Sort a list of employee dicts by salary using sorted() with a key function, ascending and descending. Practical Python sorting with live tests.

The problem

employees is a list of dicts with "name" and "salary". Return it sorted by salary, ascending.

Examples

  1. Example 1

    Input

    sort_by_salary([{'name': 'John', 'salary': 50000}, {'name': 'Alice', 'salary': 70000}, {'name': 'Bob', 'salary': 60000}])

    Expected output

    [{'name': 'John', 'salary': 50000}, {'name': 'Bob', 'salary': 60000}, {'name': 'Alice', 'salary': 70000}]

+ 2 hidden tests on Submit.

Edge cases to ask about

  • Empty list
  • Ties
  • Missing key (KeyError)

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · sort_by_salary
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    sorted(key=…)O(n log n)O(n)operator.itemgetter('salary') also works.
    Walkthrough of the optimal approach (try it yourself first)

    Same pattern as the previous question with a dict lookup in the key: sorted(employees, key=lambda e: e["salary"]). For ties broken by name, return a tuple: key=lambda e: (e["salary"], e["name"]).

    Complexity: O(n log n) time, O(n) space. A comparison sort of n records.

    Reveal the reference solution
    def sort_by_salary(employees):
        return sorted(employees, key=lambda e: e["salary"])

    Follow-ups interviewers ask

    • Descending salary, then name.
    • Some records have no salary key.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Sort a List of Dictionaries by Key in Python?

    The optimal solution runs in O(n log n) time and O(n) auxiliary space. A comparison sort of n records.

    What follow-up questions do interviewers ask about Sort a List of Dictionaries by Key?

    Descending salary, then name. Some records have no salary key.