Standard library · 16 / 17 Exercise Medium

Sorting with itemgetter

Objective

operator.itemgetter creates a function that extracts one or several items from each record. It is the clean way to sort by several criteria.

Instructions

  • Read n and then n lines with the format name age (the age is an integer).
  • Store each record as a tuple (name, age).
  • Sort them with sorted(..., key=itemgetter(1, 0)): first by age from smallest to largest and, for equal ages, by name alphabetically.
  • Show one line name age per record.
Input
4
ana 30
luis 25
eva 30
pau 25
Output
luis 25
pau 25
ana 30
eva 30

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise