Built-ins & Standard Library · Question 9 · Medium

Words are grouped by their first letter using defaultdict(list). What does the final dictionary look like?

from collections import defaultdict

groups = defaultdict(list)
for w in ["ant", "bat", "arm", "bee"]:
    groups[w[0]].append(w)
print(dict(groups))
  1. {'a': 'arm', 'b': 'bee'}
  2. {'a': ['ant', 'arm'], 'b': ['bat', 'bee']}
  3. {'a': ['ant'], 'b': ['bat']}
  4. KeyError
Answer and explanation

Answer: B. {'a': ['ant', 'arm'], 'b': ['bat', 'bee']}

Explanation: When a missing key is accessed, defaultdict(list) creates an empty list for it, so append always works. Words starting with the same letter collect in the same list, in the order seen.

Previous: A Counter is built from a list of drink orders and is then asked about a drink… · Next: A deque gets an appendleft, a pop and a rotate(1). What does it hold at the end?

Practise built-ins & standard library

Try a fresh set of built-ins & standard library questions with an explanation after every answer, free and without signing up: Built-ins & Standard Library practice. Or sit a full placement mock test.

More built-ins & standard library questions

More python practice

Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators · Classes & Objects

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge