ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
d = {}
for w in "to be or not to be".split():
    d[w] = d.get(w, 0) + 1
best = max(d, key=d.get)
print(best, sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))[:3])
  1. A. be [('be', 2), ('to', 2), ('not', 1)]
  2. B. to [('be', 2), ('to', 2), ('not', 1)]
  3. C. to [('to', 2), ('be', 2), ('or', 1)]
  4. D. to [('be', 2), ('to', 2), ('or', 1)]

Correct answer: B. to [('be', 2), ('to', 2), ('not', 1)]

max over a dict iterates its keys in insertion order and returns the first with the maximal count, 'to'. The sort key orders by count descending and then alphabetically: be, to, then 'not' before 'or'.

More Python Programming questions

Exams that ask this topic