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)
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)
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)
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)
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)