Solution: Saving and loading data

Solution: Saving and loading data

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
#%%cmd (windows)
cat 'maze.json'
{"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}}

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

Or with YAML:

import yaml
with open("maze.yaml", "w") as yaml_maze_out:
    yaml_maze_out.write(yaml.dump(house))
%%bash
#%%cmd (windows)
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
with open("maze.yaml") as yaml_maze_in:
    maze_again = yaml.safe_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']}}