ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
words = ["apple", "Banana", "cherry", "date"]
by_len = {}
for w in words:
    by_len.setdefault(len(w), []).append(w)
print(by_len, {k: len(v) for k, v in sorted(by_len.items(), reverse=True)})
  1. A. {5: ['apple'], 6: ['cherry'], 4: ['date']} {6: 1, 5: 1, 4: 1}
  2. B. {4: ['date'], 5: ['apple'], 6: ['Banana', 'cherry']} {6: 2, 5: 1, 4: 1}
  3. C. {5: ['apple'], 6: ['Banana', 'cherry'], 4: ['date']} {6: 2, 5: 1, 4: 1}
  4. D. {5: ['apple'], 6: ['Banana', 'cherry'], 4: ['date']} {4: 1, 5: 1, 6: 2}

Correct answer: C. {5: ['apple'], 6: ['Banana', 'cherry'], 4: ['date']} {6: 2, 5: 1, 4: 1}

setdefault creates each list on first sight of a length, so keys appear in first-seen order. Sorting the items in reverse orders them by key 6, 5, 4, and the dict comprehension keeps that order.

More Python Programming questions

Exams that ask this topic