Bitpath

Lesson 2 · Unit 04

Dictionaries, tuples and sets

Look up by key, unpack pairs, remember what you saw

13 exercisesabout 3 min

What you practise

  • Lookup by key and get, adding and updating, looping over items(), 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?

Python
ages = {"Ada": 36, "Bo": 41}
print(ages["Bo"])

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.

Python
stock = {"apple": 3}
stock["pear"] = 5        # add
stock["apple"] = 2       # replace
print(stock)
# {'apple': 2, 'pear': 5}
print("pear" in stock)   # True

Concept

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.

Python
prices = {"tea": 2, "cake": 4}
for item, price in prices.items():
    print(item, price)
# tea 2
# cake 4

Concept

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.

Python
seen = set()
seen.add("tea")
seen.add("tea")
seen.add("milk")
print(len(seen))         # 2
print("tea" in seen)     # True

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy