Class 10 Computer Science — Dictionaries and their keys
Look a value up in a dictionary by its key, and work out what adding a key or writing over one leaves behind.
Name: ________________________
1.A value is looked up by name rather than by position here. What does this program print?
prices = {"pen": 10, "book": 45, "bag": 90} print(prices["book"])2.Two values are looked up and added together. What does this program print?
weights = {"box": 25, "bag": 40, "cup": 5} print(weights["box"] + weights["cup"])3.A dictionary called counts holds {"pen": 4, "book": 9, "bag": 2, "map": 7, "cup": 6}. Match each piece of code to the number it gives.
- counts["book"]
- counts["map"]
- counts["pen"]
- counts["cup"]
- len(counts)
- 7
- 9
- 4
- 6
- 5
4.One of these two lines adds a pair and the other one does not. What does this program print?
stock = {"pen": 6} stock["book"] = 3 stock["pen"] = 11 print(stock["pen"] + stock["book"])5.A key the dictionary did not have is written to here. What does this program print?
stock = {"pen": 12, "book": 5} stock["bag"] = 9 print(len(stock))6.The dictionary is measured rather than looked in. What does this program print?
stock = {"red": 4, "blue": 7, "green": 2, "black": 9} print(len(stock))7.One line here both reads a value and writes one back under the same key. What does this program print?
totals = {"north": 30, "south": 12} totals["south"] = totals["south"] + 8 print(totals["south"])8.This line looks just like the last one, but the key it writes to is not new. What does this program print?
counts = {"red": 3, "blue": 8} counts["red"] = 10 print(len(counts))
Answer key — Class 10 Computer Science — Dictionaries and their keys
- 1. 45
- 2. 30
- 3. counts["book"] → 9; counts["map"] → 7; counts["pen"] → 4; counts["cup"] → 6; len(counts) → 5
- 4. 14
- 5. 3
- 6. 4
- 7. 20
- 8. 2