PythiloLesson 27 of 30 · progress kept in this browser

JSON files

JSON is a text format for nested data that almost every language can read. The json module turns dicts, lists, strings, numbers, booleans and None into JSON text and back.

import json
from pathlib import Path

data = {"name": "Ada", "langs": ["py"],
        "active": True, "boss": None}
p = Path("user.json")
with p.open("w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)

with p.open(encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded == data)  # True
  • dump and load work with files. dumps and loads, with an s for string, work with text.
  • indent=2 makes the file readable, and sort_keys=True gives a stable key order.
  • Tuples come back as lists, and dict keys always come back as strings.
  • A set cannot be saved and raises TypeError. Convert it to a list first, and back again after loading.

A JSON file is a good fit for settings and small saved state. It is plain text, so you can open it and read it.

Your task

Write save_tags(path, tags), where tags maps a name to a set of strings, saving it as JSON with indent=2 and sorted keys, each set stored as a sorted list. Write load_tags(path) reading it back with each list turned into a set again, or returning {} if the file does not exist.