Class 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.Only the values that get past the comparison reach the total here. What does the program print?
hours = {"mon": 3, "tue": 8, "wed": 2, "thu": 9} long = 0 for day in hours: if hours[day] >= 8: long = long + hours[day] print(long)2.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)
- 15
- 6
- 60
- 3
- 30
3.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])4.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)5.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)6.Nothing is looked up in this loop at all — the counter climbs by one however large the values are. What does the program print?
counts = {"red": 3, "blue": 8, "green": 1, "black": 6} n = 0 for key in counts: n = n + 1 print(n)7.Every value in this dictionary is added into a running total. What does the program print?
stock = {"pen": 4, "book": 9, "bag": 2} total = 0 for key in stock: total = total + stock[key] print(total)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 — Class 10 Computer Science — Looping over a dictionary
- 1. 17
- 2. total = total + prices[k] → 30; total = total + 1 → 3; total = total + 2 → 6; total = prices[k] → 15; total = total + (prices[k] * 2) → 60
- 3. 7
- 4. 12
- 5. 2
- 6. 4
- 7. 15
- 8. 2