XClose

An introduction to research programming with Python

Home
Menu

Solution: saving and loading a maze

An example maze data object:

In [1]:
maze = {
    'living' : {
        'exits': {
            'north' : 'kitchen',
            'outside' : 'garden',
            'upstairs' : 'bedroom'
        },
        'people' : ['James'],
        'capacity' : 2
    },
    'kitchen' : {
        'exits': {
            'south' : 'living'
        },
        'people' : [],
        'capacity' : 1
    },
    'garden' : {
        'exits': {
            'inside' : 'living'
        },
        'people' : ['Sue'],
        'capacity' : 3
    },
    'bedroom' : {
        'exits': {
            'downstairs' : 'living',
            'jump' : 'garden'
        },
        'people' : [],
        'capacity' : 1
    }
}

JSON

We can save the maze to a file using the json module as follows:

In [2]:
import json
with open('maze.json', 'w') as json_maze_out:
    json.dump(maze, json_maze_out)

We can then load the saved JSON file in to another variable as follows

In [3]:
with open('maze.json', 'r') as json_maze_in:
    loaded_maze = json.load(json_maze_in)
print(loaded_maze)
{'living': {'exits': {'north': 'kitchen', 'outside': 'garden', 'upstairs': 'bedroom'}, 'people': ['James'], 'capacity': 2}, 'kitchen': {'exits': {'south': 'living'}, 'people': [], 'capacity': 1}, 'garden': {'exits': {'inside': 'living'}, 'people': ['Sue'], 'capacity': 3}, 'bedroom': {'exits': {'downstairs': 'living', 'jump': 'garden'}, 'people': [], 'capacity': 1}}

As a sanity check we can evaluate whether the loaded maze object is equal to the maze object we first defined

In [4]:
print(loaded_maze == maze)
True

YAML

We can save the maze to a file using the yaml module as follows:

In [5]:
import yaml
with open('maze.yaml', 'w') as yaml_maze_out:
    yaml.dump(maze, stream=yaml_maze_out)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In [5], line 1
----> 1 import yaml
      2 with open('maze.yaml', 'w') as yaml_maze_out:
      3     yaml.dump(maze, stream=yaml_maze_out)

ModuleNotFoundError: No module named 'yaml'

We can then load the saved YAML file in to another variable as follows

In [6]:
with open('maze.yaml', 'r') as yaml_maze_in:
    loaded_maze = yaml.safe_load(yaml_maze_in)
print(loaded_maze)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In [6], line 1
----> 1 with open('maze.yaml', 'r') as yaml_maze_in:
      2     loaded_maze = yaml.safe_load(yaml_maze_in)
      3 print(loaded_maze)

FileNotFoundError: [Errno 2] No such file or directory: 'maze.yaml'

As a sanity check we can evaluate whether the loaded maze object is equal to the maze object house we first defined

In [7]:
print(loaded_maze == maze)
True