Project: a contacts book saved to JSON
🌍 In real life. Your phone remembers every contact you've saved, even after it's switched off and on again. A program, though, forgets everything the moment it ends: its dictionaries live only in memory. To remember, it has to save its data to a file before it ends and load it again next time.
In this project you'll build a small contacts book that does exactly that. It uses everything from World 3: functions, errors, and files with JSON.
The plan in one sentence: load the contacts from a JSON file (or start empty), carry out commands one by one, then save the contacts back to the file.
Its words:
- persistence: data that survives after the program ends, because it was saved to a file
- command: one line the user types, like
add Joy 01933-333333,find Rimi,delete Bo,listorquit - load / save: read the file into a dictionary at the start; write the dictionary back at the end
Step by step, the plan:
- Load:
load_contactsreadscontacts.json; if the file isn't there yet, it returns{}instead of crashing. - Handle:
handle(line, contacts)carries out one command and returns the message to show. - Loop: read commands until
quit, printing each message. - Save:
save_contactswrites the dictionary back as JSON.
Here are the commands working on the contacts dictionary:
Step 1: load and save. A missing file isn't a bug: it just means nobody has saved anything yet. So load_contacts catches only FileNotFoundError (Lesson 18.1) and returns an empty dictionary. Saving uses indent=2, so the file is easy for a person to read and check.
import json
def load_contacts(path):
"""The contacts saved in path, or {} if there is no such file yet."""
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return {}
print(load_contacts("contacts.json"))
print(load_contacts("missing.json"))Step 2: one function per command line. handle splits the line into words: the first is the command, the rest are its details. It returns a message instead of printing it, so it can be tested on its own, with any dictionary, without typing anything (Lesson 14.3). Each command is one small dictionary job: contacts[name] = number, contacts.get(name, ...), del contacts[name], and sorted(contacts) for the list.
import json
def load_contacts(path):
"""The contacts saved in path, or {} if there is no such file yet."""
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return {}
def save_contacts(path, contacts):
"""Write the contacts to path as JSON."""
with open(path, "w") as f:
json.dump(contacts, f, indent=2)
def handle(line, contacts):
"""Carry out one command and return the message to show."""
parts = line.split()
if not parts:
return "Unknown command"
command = parts[0]
if command == "add" and len(parts) == 3:
contacts[parts[1]] = parts[2]
return f"Saved {parts[1]}"
if command == "find" and len(parts) == 2:
return contacts.get(parts[1], f"{parts[1]} not found")
if command == "delete" and len(parts) == 2:
if parts[1] in contacts:
del contacts[parts[1]]
return f"Deleted {parts[1]}"
return f"{parts[1]} not found"
if command == "list" and len(parts) == 1:
if not contacts:
return "No contacts"
return "\n".join(f"{name}: {contacts[name]}" for name in sorted(contacts))
return "Unknown command"
contacts = load_contacts("contacts.json")
while True:
line = input()
if line == "quit":
break
print(handle(line, contacts))
save_contacts("contacts.json", contacts)
print(f"Saved {len(contacts)} contacts")Why build it this way, and what it costs. Each piece has one job and a clear name, so each can be tested and fixed on its own: a wrong message is a bug in handle, a lost contact is a bug in saving. Every command is a dictionary operation that takes about the same time however many contacts there are; only list walks them all (and sorts them). Loading and saving read and write the whole file once per run.
Mistakes and edge cases.
- Catching every error in load.
except Exception:would also hide a broken JSON file, and the program would then save{}over it, deleting every contact. Catch onlyFileNotFoundError. - Forgetting to save. Changes made in the loop are lost if the program ends before
save_contacts. - A command with the wrong number of words.
add Joy(no number) shouldn't crash;handlecheckslen(parts)and answers "Unknown command". - Names with spaces.
add Rimi Akter 0171...has four words; this simple version keeps names to one word.
Quiz
What does this print?
parts = "add Joy 01933".split() print(parts[0], len(parts))What does this print?
contacts = {"Rimi": "0171"} print(contacts.get("Zed", "Zed not found"))A friend's contacts.json got a typo in it, and after one run every contact was gone. Which line caused that?
def load_contacts(path): try: with open(path) as f: return json.load(f) except Exception: return {}Why does handle return its message instead of printing it?
- So it can be tested and reused without typing anything
- Because print can't show strings with spaces
- Because functions aren't allowed to print
What does this print?
import json saved = json.dumps({"Bo": "0182"}) print(json.loads(saved)["Bo"])
Coding tasks
Step 1: load the contacts. Write
load_contacts(path). It returns the dictionary saved as JSON in the filepath, or{}if there is no such file. Catch onlyFileNotFoundError. Acontacts.jsonfile comes with the task.Step 2: handle one command. Write
handle(line, contacts), which carries out one command on the dictionary and returns the message:add NAME NUMBER→ store it, returnSaved NAMEfind NAME→ return the number, orNAME not founddelete NAME→ remove it and returnDeleted NAME, orNAME not foundlist→ every contact asNAME: NUMBER, sorted by name, one per line, orNo contacts- anything else →
Unknown command
Step 3: the whole program. Add
save_contacts(path, contacts)if you haven't, then the main part: loadcontacts.json, read commands withinput()untilquit, print each message fromhandle, save the contacts back tocontacts.json, and finally printSaved N contacts.