Consider the Python program below.
words = "the cat and the dog and the bird".split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)
print(max(freq, key=freq.get))(a) State the output of the program. [3]
(b) Outline the purpose of freq.get(w, 0). [1]
- First line of output is the dictionary with the, cat, and, dog, bird in order of first appearance(1)
- Counts are correct: the 3, cat 1, and 2, dog 1, bird 1 →
{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}(ignore quote style and spacing)(1) - Second line of output is
the(the key with the highest value)(1) - (b) Returns the current count for
w, or 0 ifwis not yet a key, so a new word starts at 0 and no KeyError is raised (accept either idea)(1) - Answer: {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1} then the
- Examiner tip: Dictionaries keep insertion order in Python 3.7+, so the printed order follows first appearance.