CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / Build with Python

Dictionaries: Labels, Not Numbers

Lesson 6 of 12 · 7 min · Free, no account needed

What you will learn

  • A dictionary stores key: value pairs: scores = {"Mia": 12}.
  • scores["Mia"] goes straight to the drawer labelled Mia. No searching.
  • scores["Zoe"] = 5 adds a new drawer, or replaces the value if Zoe is already there.
  • Asking for a key that isn't there gives a KeyError; check first with "Zoe" in scores.

Start the lesson

How the lesson goes

  1. Your friends' high scores, in a list. Where's Mia?

    A list only knows positions 0, 1, 2. Open lockers until you find her.

  2. What does this print?

    Curly brackets make a dictionary. Drag your bet into the output.

  3. Step through it. Watch the drawers.

    A lookup opens one drawer. A new key adds one.

  4. Dictionaries: keys and values.

    A dictionary holds key: value pairs in curly brackets. The key is the label, the value is inside.

    d[key] reads a value. d[key] = value writes one: a new key makes a new drawer, an old key gets its value replaced.

    key in d is True or False. Reading a key that isn't there stops the program with a KeyError.

  5. Trace it yourself.

    For each line, drag the new value onto the drawer it changes, or onto new drawer.

  6. Max has no score yet, and the program crashes. Make it safe.

    Run it, read the error, then fix the if line.

  7. Build a token dictionary, the way an AI reads text.

    Each new word gets the next number. A word you've seen before goes into its old drawer.

  8. Drawer dash: answer each lookup fast.

    Tap the drawer whose value it gives, or a lamp: True, False or KeyError.

  9. List or dictionary? Sort the jobs.

    Order and positions: list. Look up by a name: dictionary.

  10. Decode a secret with your token dictionary.

    Each number is a word's id. Tap the drawers in order.

Previous lesson: Loops Inside Loops · Next lesson: Counting with a Dictionary · Part of the course: Build with Python

Lessons are interactive and need JavaScript. Turn it on to play them.

Loading TwiddleLab