Sort products by price then name

Python data engineering interview problem. Difficulty: beginner. Pattern: Sorting. About 10 minutes. Free to practice.

A catalog export needs products listed by price, and by name when prices tie, so two $12 items do not swap order between runs.

A product list should look predictable: cheaper products first, and products with the same price sorted by name. Sort a list of product dictionaries by price (small to large), and by name (A to Z) when the prices are equal. Return a new list. Write sort_products(products). For products b (price 2), a (price 2) and c (price 1), the order is c first (cheapest), then a and b (same price, so by name). The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Sort by price ascending.
  • Break ties by name ascending.
  • Return a new list.
  • Return [] for an empty list.

Constraints

  • Each product is a dictionary with name and price.
  • Prices are numbers.

Examples

Input: sort_products([{'name': 'b', 'price': 2}, {'name': 'a', 'price': 2}, {'name': 'c', 'price': 1}]) Output: [{'name': 'c', 'price': 1}, {'name': 'a', 'price': 2}, {'name': 'b', 'price': 2}] This input follows the stated rules and produces this output.

Topics: lakebench, python, sorting.

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

beginner

Sort products by price then name

Interview-style drill: Sort a list of product records by price ascending, breaking ties alphabetically.

Sort products by price, then by name for ties.