ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from itertools import groupby
rows = [('b', 2), ('a', 1), ('b', 5), ('a', 3)]
ok = {k: sum(v for _, v in g) for k, g in groupby(sorted(rows), key=lambda r: r[0])}
bad = {k: sum(v for _, v in g) for k, g in groupby(rows, key=lambda r: r[0])}
print(ok, bad)
  1. A. {'a': 4, 'b': 7} {'a': 4, 'b': 7}
  2. B. {'b': 7, 'a': 4} {'b': 5, 'a': 3}
  3. C. {'a': 4, 'b': 7} {'b': 5, 'a': 3}
  4. D. {'a': 4, 'b': 7} {'a': 3, 'b': 5}

Correct answer: C. {'a': 4, 'b': 7} {'b': 5, 'a': 3}

groupby merges only consecutive equal keys, so on the unsorted rows the later groups overwrite earlier dict entries. Sorting first gives the true totals.

More Python Programming questions

Exams that ask this topic