Solution

The solution notebook can be downloaded from:

https://anaconda.org/ucl-rits/module16-mazefilessolution/notebook

house = {
    '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
    }
}

Save the maze with json:

import json
with open('maze.json','w') as json_maze_out:
    json_maze_out.write(json.dumps(house))

Consider the file on the disk:

%%bash
cat 'maze.json'

« {“living”: {“exits”: {“upstairs”: “bedroom”, “north”: “kitchen”, “outside”: “garden”}, “people”: [“James”], “capacity”: 2}, “bedroom”: {“exits”: {“jump”: “garden”, “downstairs”: “living”}, “people”: [], “capacity”: 1}, “garden”: {“exits”: {“inside”: “living”}, “people”: [“Sue”], “capacity”: 3}, “kitchen”: {“exits”: {“south”: “living”}, “people”: [], “capacity”: 1}}

and now load it into a different variable:

with open('maze.json') as json_maze_in:
    maze_again = json.load(json_maze_in)
maze_again

« {‘bedroom’: {‘capacity’: 1, ‘exits’: {‘downstairs’: ‘living’, ‘jump’: ‘garden’}, ‘people’: []}, ‘garden’: {‘capacity’: 3, ‘exits’: {‘inside’: ‘living’}, ‘people’: [‘Sue’]}, ‘kitchen’: {‘capacity’: 1, ‘exits’: {‘south’: ‘living’}, ‘people’: []}, ‘living’: {‘capacity’: 2, ‘exits’: {‘north’: ‘kitchen’, ‘outside’: ‘garden’, ‘upstairs’: ‘bedroom’}, ‘people’: [‘James’]}}

Or with YAML:

import yaml
with open('maze.yaml','w') as yaml_maze_out:
    yaml_maze_out.write(yaml.dump(house))
%%bash
cat 'maze.yaml'

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

</span>

with open('maze.yaml') as yaml_maze_in:
    maze_again = yaml.load(yaml_maze_in)
maze_again

« {‘bedroom’: {‘capacity’: 1, ‘exits’: {‘downstairs’: ‘living’, ‘jump’: ‘garden’}, ‘people’: []}, ‘garden’: {‘capacity’: 3, ‘exits’: {‘inside’: ‘living’}, ‘people’: [‘Sue’]}, ‘kitchen’: {‘capacity’: 1, ‘exits’: {‘south’: ‘living’}, ‘people’: []}, ‘living’: {‘capacity’: 2, ‘exits’: {‘north’: ‘kitchen’, ‘outside’: ‘garden’, ‘upstairs’: ‘bedroom’}, ‘people’: [‘James’]}}