Grade 10 Computer Science — Looping over a dictionary
Follow a loop that visits every key in a dictionary, looks each value up, and leaves a total or a count behind.
Name: ________________________
1.A program sets total to 0 and then runs "for k in prices:" over the dictionary {"pen": 5, "bag": 10, "cup": 15}, with one of these lines as the body. Match each body to what total holds at the end.
- total = total + prices[k]
- total = total + 1
- total = total + 2
- total = prices[k]
- total = total + (prices[k] * 2)
- 30
- 15
- 3
- 60
- 6
2.Two separate loops here feed the same total, one after the other. What does the program print?
left = {"pen": 3, "bag": 4} right = {"cup": 5} total = 0 for k in left: total = total + left[k] for k in right: total = total + right[k] print(total)3.This loop keeps hold of two things at once: the best value it has seen, and the key that value came from. Which word does the program print?
votes = {"red": 12, "blue": 30, "green": 21} best = "" top = 0 for name in votes: if votes[name] > top: top = votes[name] best = name print(best)4.This loop prints as it goes, and a dictionary is walked in the order its pairs were written. What is the last number it prints?
sizes = {"small": 2, "large": 7} for name in sizes: print(sizes[name])5.A loop counts how many of a dictionary's values are over 10. Put these dictionaries in order of that count, fewest first.
- {"pen": 12, "bag": 3}
- {"pen": 4, "bag": 2}
- {"pen": 15, "bag": 20, "cup": 30}
- {"pen": 11, "bag": 40, "cup": 2}
6.A loop over a dictionary is written as "for name in sizes:". What does name hold each time round?
- a) A position, counting from 0
- b) A whole pair, key and value together
- c) One of the keys
- d) One of the values
7.There is a decision inside this loop, so not every key adds to the counter. What does the program print?
sales = {"north": 12, "south": 30, "east": 5, "west": 22} busy = 0 for place in sales: if sales[place] > 20: busy = busy + 1 print(busy)8.A dictionary is built from scratch inside this loop, and one thing in the list turns up twice. What does the program print?
counts = {} for word in ["pen", "bag", "pen"]: counts[word] = 1 print(len(counts))
Answer key — Grade 10 Computer Science — Looping over a dictionary
- 1. total = total + prices[k] → 30; total = total + 1 → 3; total = total + 2 → 6; total = prices[k] → 15; total = total + (prices[k] * 2) → 60
- 2. 12
- 3. blue
- 4. 7
- 5. 1. {"pen": 4, "bag": 2} 2. {"pen": 12, "bag": 3} 3. {"pen": 11, "bag": 40, "cup": 2} 4. {"pen": 15, "bag": 20, "cup": 30}
- 6. c) One of the keys
- 7. 2
- 8. 2