Lesson 2 · Unit 04
Dictionaries, tuples and sets
Look up by key, unpack pairs, remember what you saw
What you practise
- Lookup by key and
get, adding and updating, looping overitems(), tuples and unpacking, sets for "have I seen this?"
Try a question from this lesson
Pick one
A dictionary stores pairs: a key and the value that goes with it. You look a value up by its key. What does this show?
ages = {"Ada": 36, "Bo": 41}
print(ages["Bo"])Correct answer
41
Why
The square brackets hold a key this time, not a position. The dictionary finds the pair whose key is "Bo" and hands back its value, 41.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Dictionaries
A dictionary is written in curly brackets as key: value pairs.
d[key] looks a value up. Giving a value to d[key] adds a new pair, or replaces the value if the key is already there.
len counts the pairs, and in asks whether a key is present.
stock = {"apple": 3}
stock["pear"] = 5 # add
stock["apple"] = 2 # replace
print(stock)
# {'apple': 2, 'pear': 5}
print("pear" in stock) # TrueConcept
Looping over a dictionary
d.items() hands out the pairs one at a time, in the order they were added.
Put two names after for and each pair is split between them: the key goes to the first name and the value to the second.
prices = {"tea": 2, "cake": 4}
for item, price in prices.items():
print(item, price)
# tea 2
# cake 4Concept
Sets
A set holds each value only once, in no particular order.
It is the right tool for the question "have I seen this before?": add puts a value in and quietly ignores repeats, and in checks whether a value is there.
set(...) also turns a list into a set, dropping the repeats.
seen = set()
seen.add("tea")
seen.add("tea")
seen.add("milk")
print(len(seen)) # 2
print("tea" in seen) # True9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.