Python 12 · Draw the moonbase as a dictionary

Python lesson 12 of 50 · Early intermediate · About 30 minutes

Draw four connected rooms in code so Pip can inspect a location and see where its doors lead.

Pip sits at the crossing of moon tracks near the lit Workshop and Greenhouse, with a beacon on a far ridge.

Mission Keep the description and exits for each room together in a nested dictionary.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Open the browser Python editor (opens in a new tab), replace its example with the complete checkpoint below and choose Run. Use Python 3.10 or newer.

Name the rooms. Use a top-level key for each place.. → Store the doors. Put directions inside each room record.. → Inspect the map. Read the record for Pip’s current room..
Name the rooms → Store the doors → Inspect the map

Understand the Python in this lesson

Read the explanations, then follow the worked example before changing the code.

Read the room map in layers

WORLD is a dictionary whose keys are room names. Each room points to another dictionary with a "scene" and "exits". The braces around the exits create a third dictionary. Its keys are directions and its values are the room names reached in those directions.

Separate the map from the player

WORLD describes where the doors lead. state["room"] tells the game where Pip is right now. The uppercase name WORLD is a clue for the reader that this data is meant to stay fixed during a mission. Python still treats it like an ordinary dictionary.

Follow the two lookups

Inside look(state), the first assignment copies Pip’s current room name into room. The next uses that name as a key in WORLD[room]. Leaving the quotes off room tells Python to use its stored value, such as "Habitat". The resulting room dictionary is stored in info.

Show the doors as a line of text

", ".join(info["exits"]) joins the exit dictionary’s keys with a comma and a space. Those keys are the directions in the order they were written. The indented instructions belong to the function. The final unindented look(state) call runs them.

How the pieces fit The map gives the code one place to find scene descriptions and door rules. The next lessons can use those same doors for commands and movement.

Follow one run, step by step
  1. Read Pip’s room from state
    room is "Habitat". Why The starting state names one room in the map.
  2. Use WORLD[room]
    info contains Habitat’s scene and exits. Why Python uses the stored name to find the matching room record.
  3. Show the scene
    Pip wakes in the Habitat. Why The "scene" key holds that sentence.
  4. Join the exit keys
    Exits: north, east Why The dictionary’s keys describe the choices the player can type.

Predict before you run What will look(state) show if the starting room is "Beacon"?

Reveal the explanation

It prints The Beacon stands quiet. and Exits: west, south. The function reads the same two keys in a different room record.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills Nested dictionaries, Lookup chains, Separated map and state.

1. Give every room an address

On paper draw a square. Put the Habitat at the bottom left, Workshop above it, Greenhouse to the right of Habitat and Beacon above Greenhouse. Each key in WORLD names one room. The value for that key groups the room’s scene and a dictionary of exits. Use the same room names as the labels on your sketch.

WORLD = {
    "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}},
    "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}},
    "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}},
    "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}},
}

2. Follow the lookup

The look function reads Pip’s current room from state. It then uses the room name to look up the room record in WORLD. Keep these lookups on two lines so you can describe the value of each variable. Finally print the description and join the exit names with a comma and a space.

def look(state):
    room = state["room"]
    info = WORLD[room]
    print(info["scene"])
    print("Exits:", ", ".join(info["exits"]))

3. Check both ends of a door

Trace the Habitat’s north exit to the Workshop. Then check the Workshop’s south exit leads back to the Habitat. Python treats the two exits as independent entries. Fix the return direction if your map accidentally leaves Pip stranded. To inspect a different room without adding movement yet, change the starting room in state and rerun.

state = {
    "room": "Habitat",
    "energy": 8,
    "parts": [],
    "rescued": False,
}
Complete Python checkpoint · moonbase_12.py
WORLD = {
    "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}},
    "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}},
    "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}},
    "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}},
}

state = {
    "room": "Habitat",
    "energy": 8,
    "parts": [],
    "rescued": False,
}

def look(state):
    room = state["room"]
    info = WORLD[room]
    print(info["scene"])
    print("Exits:", ", ".join(info["exits"]))

look(state)

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–21
Lines 1–6 WORLD = { "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}}, "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}}, "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}}, "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Lines 8–13 state = { "room": "Habitat", "energy": 8, "parts": [], "rescued": False, }
Work out the value on the right, then store it in state. Each colon pairs a key with its value.
Line 15 def look(state):
Define look, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 16 room = state["room"]
Work out the value on the right, then store it in room. The brackets look up a dictionary key or a position that starts at zero.
Line 17 info = WORLD[room]
Work out the value on the right, then store it in info. The brackets look up a dictionary key or a position that starts at zero.
Line 18 print(info["scene"])
Show the message or value in the output. The brackets look up a dictionary key or a position that starts at zero.
Line 19 print("Exits:", ", ".join(info["exits"]))
Show the message or value in the output. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 21 look(state)
Run look with the supplied inputs and come back here when it returns.

Test the mission

  • Set the starting room to Beacon and check that both west and south are listed.
  • Read each direction pair out loud while your finger traces the paper map.

If something goes wrong

A room with a space or different capital letter fails to load.
Copy the exact room key from WORLD into state so the lookup finds the room.

Mission extension

Add one line of description to the Greenhouse and use the starting room to check it.