← Deeper Python in the console

A map of rooms

Store rooms and exits in dictionaries, look things up by name, put a dictionary inside a dictionary, and count words.

A phone's contacts, a dictionary app and a game's map all do the same thing: look something up by its name.

A list finds things by place: words[0]. A dictionary finds things by name: exits["north"] is wherever north leads. The adventure keeps its rooms in one dictionary and its exits in another.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

rooms.py
exits = {"north": "kitchen", "east": "garden"}
print(exits["north"])
print("west" in exits)

{"north": "kitchen", "east": "garden"} pairs each key with a value. exits["north"] looks up the value for that key. What does it print?

What is the first line it prints?

RunRun it and compare the result with your prediction.

Run

Walk around: go north, go south, go east, go west, then quit. rooms maps each room's name to its description. exits maps each room's name to another dictionary of its exits, so exits[here]["north"] is where north leads from here.

rooms.py
rooms = {
    "hall": "A long hall with a creaky floor.",
    "kitchen": "A kitchen that smells of toast.",
    "garden": "A garden full of tall grass.",
}
exits = {
    "hall": {"north": "kitchen", "east": "garden"},
    "kitchen": {"south": "hall"},
    "garden": {"west": "hall"},
}
here = "hall"
while True:
    print(rooms[here])
    print("Exits: " + ", ".join(exits[here]))
    command = input("> ").strip().lower()
    words = command.split()
    if command == "quit":
        break
    elif len(words) == 2 and words[0] == "go":
        if words[1] in exits[here]:
            here = exits[here][words[1]]
        else:
            print("You can't go that way.")
    else:
        print("Try: go north, or quit")
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

rooms.py
rooms = {
    "hall": "A long hall with a creaky floor.",
    "kitchen": "A kitchen that smells of toast.",
    "garden": "A garden full of tall grass.",
}
exits = {
    "hall": {"north": "kitchen", "east": "garden"},
    "kitchen": {"south": "hall"},
    "garden": {"west": "hall"},
}
here = "hall"
while True:
    print(rooms[here])
    print("Exits: " + ", ".join(exits[here]))
    command = input("> ").strip().lower()
    words = command.split()
    if command == "quit":
        break
    elif len(words) == 2 and words[0] == "go":
        if words[1] in exits[here]:
            here = exits[here][words[1]]
        else:
            print("You can't go that way.")
    else:
        print("Try: go north, or quit")

Look up one exit.

What in protects against.

A key that is nearly right.

What is exits["hall"]["east"]?

You are in the kitchen and type go west. What happens?

This stops with KeyError: Hall. Click the line that causes it.

ModifyChange the code on purpose and check the result.

Modify

Add an attic, reached by go up from the hall (and go down back).

Need a hint?

Add "attic": "..." to rooms, and "attic": {"down": "hall"} to exits.

Another hint

Then add "up": "attic" to the hall's exits.

Count each move, and say how many when the player quits.

Need a hint?

Start moves = 0 before the loop, add moves += 1 when the player moves, and print it when they quit.

Try it yourselfYour edits are saved in this browser.

Add an attic, up from the hall.

    Run your program. This ticks when your code does all of the above.

    Count the moves and say how many when the player quits.

      Run your program. This ticks when your code does all of the above.

      MakeBuild something new using what you have learned. Expect a few tries; that is normal.

      Make a word counter

      Ask for a sentence and print how many times each word appears, such as the: 3. Start with an empty dictionary, counts = {}. For each word: if it is already a key, add 1; if not, set it to 1. Tidy the sentence first so that The and the count as the same word.

      Try it yourselfYour edits are saved in this browser.

      Count how many times each word appears in a sentence, using a dictionary.

        Run your program. This ticks when your code does all of the above.

        Info

        Where this leads

        You now have the parts of a text adventure: a command parser, a bag and a map. Still to come in this course: handling errors with try, saving and loading a game in a file, and the adventure itself.

        A game stores each player's score by name: scores["Ada"] = 12. What is scores?

        For teachers

        Students store a map in dictionaries (rooms by name, and each room's exits), look values up by key, check keys with in, use a dictionary inside a dictionary, and count words with a dictionary. About 50 minutes.

        Open the teacher guide: answers, solutions, slides and a worksheet.

        Students will be able to

        Before class

        Read the unit primer first. A dictionary pairs keys with values: {"north": "kitchen"}; exits["north"] looks up the value. Keys must match exactly (the bug task: "Hall" is not "hall", so KeyError). "west" in exits checks for a key. exits[here] is itself a dictionary, so exits[here]["north"] looks up twice. ", ".join(exits[here]) joins the keys. Counting with a dictionary (the Make task) is a classic pattern: a new key starts at 1, an existing one goes up by 1.

        Running the lesson

        1. Predict: draw the dictionary as a two-column table, key and value.
        2. Run: draw the map (hall in the middle, kitchen north, garden east) and walk it with the class.
        3. Investigate: read exits["hall"]["east"] in two steps: the hall's exits, then east.
        4. Bug task: ask what Hall and hall have in common, and what Python thinks.
        5. Make: act it out with words on cards. A new word gets a tally of 1; a word seen before gets another tally.

        The hard part (on purpose)

        A dictionary of dictionaries: two lookups in one line. Have them say each step aloud (which room, then which way) before writing rooms[here][way].

        When students get stuck

        Stretch and support

        Stretch: Put things in rooms (a dictionary from room to a list of things) and let the player take them into last lesson's bag.

        Support: Give students the loop over the words and the if, and ask them to fill in the two lines that count.

        Where it leads

        This completes the lessons that run in the turtle playground. Still to come: errors with try, saving the game to a file, and the text adventure, which joins the parser, the bag and the map. Data detective uses lists of dictionaries for real data.

        What each step is for

        Now you can
        Next lesson4. When things go wrongCatch an error with try and except, so a typing mistake gets a helpful reply and the program asks again.