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) # Truedumpandloadwork with files.dumpsandloads, with an s for string, work with text.indent=2makes the file readable, andsort_keys=Truegives a stable key order.- Tuples come back as lists, and dict keys always come back as strings.
- A
setcannot be saved and raisesTypeError. 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.
The explanation opens here once every check passes.