ProgrammingModerateTCS NQT · Wipro pattern

What is printed?

What is printed?
from collections import defaultdict
d = defaultdict(int)
for w in 'a b a c'.split():
    d[w] += 1
print(sorted(d.items(), key=lambda kv: (-kv[1], kv[0])))
  1. A. [('a', 2), ('c', 1), ('b', 1)]
  2. B. [('a', 2), ('b', 1), ('c', 1)]
  3. C. [('b', 1), ('a', 2), ('c', 1)]
  4. D. [('a', 2), ('b', 1)]

Correct answer: B. [('a', 2), ('b', 1), ('c', 1)]

The counts are a=2, b=1 and c=1. The key sorts by descending count and then alphabetically, so the order is a, b, c.

More Python Programming questions

Exams that ask this topic