Grade 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.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"])2.You want to find one particular thing that a program has stored. What is the difference between a list and a dictionary here?
- a) A dictionary is looked in by position as well, starting from 0 like a list does
- b) A list can hold only numbers, and a dictionary only writing
- c) A dictionary numbers its keys as they go in, so its first key is key 0
- d) A list is looked in by position, and a dictionary by a key that whoever wrote the program chose
3.A dictionary called scores holds {"red": 14, "blue": 6, "green": 22, "black": 9}. Put these lookups in order of the number each one gives, smallest first.
- scores["blue"]
- scores["black"]
- scores["red"]
- scores["green"]
4.A dictionary called sizes already holds the keys small, medium and large. Sort each line by what it does to the dictionary.
Groups: Adds a new pair · Changes a pair already there
- sizes["large"] = 1
- sizes["small"] = 4
- sizes["giant"] = 6
- sizes["tiny"] = 2
- sizes["medium"] = 7
- sizes["huge"] = 9
5.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"])6.This dictionary starts with nothing in it at all. What does this program print?
seen = {} seen["pen"] = 2 seen["bag"] = 5 print(len(seen))7.A dictionary holds the keys pen, book and bag. A program then asks it for the value under the key cup. Why is that a mistake?
- a) The key cup would have to be a number rather than a word
- b) There is no such key, so there is no value for the dictionary to give back
- c) Keys have to be looked up in the order they were put in
- d) A dictionary can only be asked for one of its keys once
8.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))
Answer key — Grade 10 Computer Science — Dictionaries and their keys
- 1. 14
- 2. d) A list is looked in by position, and a dictionary by a key that whoever wrote the program chose
- 3. 1. scores["blue"] 2. scores["black"] 3. scores["red"] 4. scores["green"]
- 4. sizes["small"] = 4 → Changes a pair already there; sizes["huge"] = 9 → Adds a new pair; sizes["large"] = 1 → Changes a pair already there; sizes["tiny"] = 2 → Adds a new pair; sizes["medium"] = 7 → Changes a pair already there; sizes["giant"] = 6 → Adds a new pair
- 5. 45
- 6. 2
- 7. b) There is no such key, so there is no value for the dictionary to give back
- 8. 3