Year 11 Computing — 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 loop adds every value of a dictionary into a total that starts at 0. Sort each dictionary by the total that loop reaches.
Groups: The total comes to 10 · The total comes to 20
- {"pen": 3, "bag": 3, "cup": 4}
- {"pen": 15, "bag": 5}
- {"pen": 6, "bag": 6, "cup": 8}
- {"pen": 1, "bag": 9}
- {"pen": 8, "bag": 12}
- {"pen": 4, "bag": 6}
2.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)3.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))4.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)5.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
- 6
- 3
- 60
6.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])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 loop counts how many of a dictionary's values are over 10. Put these dictionaries in order of that count, fewest first.
- {"pen": 15, "bag": 20, "cup": 30}
- {"pen": 12, "bag": 3}
- {"pen": 4, "bag": 2}
- {"pen": 11, "bag": 40, "cup": 2}
Answer key — Year 11 Computing — Looping over a dictionary
- 1. {"pen": 4, "bag": 6} → The total comes to 10; {"pen": 15, "bag": 5} → The total comes to 20; {"pen": 3, "bag": 3, "cup": 4} → The total comes to 10; {"pen": 8, "bag": 12} → The total comes to 20; {"pen": 1, "bag": 9} → The total comes to 10; {"pen": 6, "bag": 6, "cup": 8} → The total comes to 20
- 2. 2
- 3. 2
- 4. 17
- 5. total = total + prices[k] → 30; total = total + 1 → 3; total = total + 2 → 6; total = prices[k] → 15; total = total + (prices[k] * 2) → 60
- 6. 7
- 7. 15
- 8. 1. {"pen": 4, "bag": 2} 2. {"pen": 12, "bag": 3} 3. {"pen": 11, "bag": 40, "cup": 2} 4. {"pen": 15, "bag": 20, "cup": 30}