ProgrammingHardTCS CodeVita · Infosys HackWithInfy · Product Company SDE

What does the following Python 3 code print? d = {} for w in ["nut","kheer","tea","oat","nut","vada"]: d[w[0]] = d.get(w[0], 0) + 1 print(sorted(d.items()))

  1. A. [('kheer', 1), ('nut', 2), ('oat', 1), ('tea', 1), ('vada', 1)]
  2. B. [('a', 2), ('r', 1), ('t', 3)]
  3. C. [('k', 2), ('n', 3), ('o', 2), ('t', 2), ('v', 2)]
  4. D. [('k', 1), ('n', 2), ('o', 1), ('t', 1), ('v', 1)]

Correct answer: D. [('k', 1), ('n', 2), ('o', 1), ('t', 1), ('v', 1)]

Counting by first letter: get(key, 0)+1 builds a frequency map; sorted() orders the (key, count) pairs. Output: [('k', 1), ('n', 2), ('o', 1), ('t', 1), ('v', 1)].

More Python Programming questions

Exams that ask this topic