ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
d = {'pen': 3, 'cap': 5, 'ink': 3, 'box': 1}
print(sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))[:3])
  1. A. [('ink', 3), ('pen', 3), ('cap', 5)]
  2. B. [('cap', 5), ('ink', 3), ('box', 1)]
  3. C. [('cap', 5), ('ink', 3), ('pen', 3)]
  4. D. [('cap', 5), ('pen', 3), ('ink', 3)]

Correct answer: C. [('cap', 5), ('ink', 3), ('pen', 3)]

The key sorts by count descending, using the negation, and by name ascending on ties. cap is the largest, then ink and pen tie at 3 and are ordered by name.

More Python Programming questions

Exams that ask this topic