Python 3D Academyবাংলা

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, list or quit
  • load / save: read the file into a dictionary at the start; write the dictionary back at the end

Step by step, the plan:

  1. Load: load_contacts reads contacts.json; if the file isn't there yet, it returns {} instead of crashing.
  2. Handle: handle(line, contacts) carries out one command and returns the message to show.
  3. Loop: read commands until quit, printing each message.
  4. Save: save_contacts writes 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")
The program loads Rimi and Bo, finds Rimi, adds Joy, lists all three in order, and saves them.

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 only FileNotFoundError.
  • 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; handle checks len(parts) and answers "Unknown command".
  • Names with spaces. add Rimi Akter 0171... has four words; this simple version keeps names to one word.

Quiz

  1. What does this print?

    parts = "add Joy 01933".split()
    print(parts[0], len(parts))
  2. What does this print?

    contacts = {"Rimi": "0171"}
    print(contacts.get("Zed", "Zed not found"))
  3. 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 {}
  4. 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
  5. What does this print?

    import json
    saved = json.dumps({"Bo": "0182"})
    print(json.loads(saved)["Bo"])

Coding tasks

  1. Step 1: load the contacts. Write load_contacts(path). It returns the dictionary saved as JSON in the file path, or {} if there is no such file. Catch only FileNotFoundError. A contacts.json file comes with the task.

  2. 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, return Saved NAME
    • find NAME → return the number, or NAME not found
    • delete NAME → remove it and return Deleted NAME, or NAME not found
    • list → every contact as NAME: NUMBER, sorted by name, one per line, or No contacts
    • anything else → Unknown command
  3. Step 3: the whole program. Add save_contacts(path, contacts) if you haven't, then the main part: load contacts.json, read commands with input() until quit, print each message from handle, save the contacts back to contacts.json, and finally print Saved N contacts.