In this project you build a contact book that runs in the terminal and remembers its data. When you finish you will have a program of about a hundred lines that uses dictionaries, functions, loops, exceptions, files, JSON and tests, all in one place.
What the program does
The user sees a menu and can add a contact, search by part of a name, list everyone, delete a contact or quit. Contacts are saved to a file called contacts.json, so they are still there the next time the program runs.
We build it in four steps. All the sample data is made up. The examples save into a temporary folder that Python creates and later deletes, so running them touches none of your files. The typed menu choices in the last step are simulated for the lesson.
Step 1: the data and the functions that change it
Each contact has a name and some details. We keep them in one dictionary: the name is the key, and the value is another dictionary holding the phone number and email. The functions below take that dictionary as a parameter and do not print or ask for input, which keeps them simple to test:
def add_contact(contacts, name, phone, email=""):
name = name.strip()
if not name:
raise ValueError("a contact needs a name")
if name in contacts:
raise ValueError(f"{name} is already in the book")
contacts[name] = {"phone": phone.strip(), "email": email.strip()}
def find_contacts(contacts, text):
text = text.strip().lower()
return {name: info for name, info in contacts.items() if text in name.lower()}
def delete_contact(contacts, name):
return contacts.pop(name, None) is not None
def format_contact(name, info):
line = f"{name}: {info['phone']}"
if info["email"]:
line += f" ({info['email']})"
return line
book = {}
add_contact(book, "Asha Verma", "555-0101", "asha@example.com")
add_contact(book, "Ben Carter", "555-0102")
add_contact(book, "Chloe Dubois", "555-0103")
for name, info in book.items():
print(format_contact(name, info))
print(list(find_contacts(book, "ASHA")))
print(delete_contact(book, "Ben Carter"), delete_contact(book, "Nobody"))
print(sorted(book))Asha Verma: 555-0101 (asha@example.com)
Ben Carter: 555-0102
Chloe Dubois: 555-0103
['Asha Verma']
True False
['Asha Verma', 'Chloe Dubois']A few details are worth noticing. find_contacts lowercases both sides, so the search ignores capital letters. The dictionary comprehension builds a new dictionary of the matches. contacts.pop(name, None) removes the key and returns its value, or None when the name is missing, so delete_contact can report whether anything was deleted.
Adding the same name twice is refused rather than silently overwriting:
add_contact(book, "Asha Verma", "555-9999")ValueError: Asha Verma is already in the bookStep 2: saving to and loading from JSON
JSON is a text format that maps closely onto Python dictionaries, lists, strings and numbers. json.dump writes a dictionary into an open file, and json.load reads it back. Add these two functions:
import json
import tempfile
from pathlib import Path
def load_contacts(path):
path = Path(path)
if not path.exists():
return {}
try:
with path.open(encoding="utf-8") as file:
return json.load(file)
except json.JSONDecodeError:
raise ValueError(f"{path.name} is not valid JSON")
def save_contacts(path, contacts):
with Path(path).open("w", encoding="utf-8") as file:
json.dump(contacts, file, indent=2, sort_keys=True)
workdir = tempfile.TemporaryDirectory()
data_file = Path(workdir.name) / "contacts.json"
print(load_contacts(data_file))
save_contacts(data_file, book)
print(data_file.read_text(encoding="utf-8"))
print(load_contacts(data_file) == book){}
{
"Asha Verma": {
"email": "asha@example.com",
"phone": "555-0101"
},
"Chloe Dubois": {
"email": "",
"phone": "555-0103"
}
}
TrueOn the first run the file does not exist, so load_contacts returns an empty dictionary and everything else works as normal. After saving you can see the file text: it is readable and indented because of indent=2, and sort_keys=True keeps the order stable. Loading it back gives a dictionary equal to the one we saved.
If someone damages the file by hand, loading it should give a clear message and not a confusing traceback, which is what the except clause does:
bad_file = Path(workdir.name) / "broken.json"
bad_file.write_text("{not valid json", encoding="utf-8")
try:
load_contacts(bad_file)
except ValueError as error:
print("Problem:", error)Problem: broken.json is not valid JSONStep 3: the menu
Now connect everything to a menu. The simulated-input helper below is only for this lesson. It feeds in typed answers and shows them as they would look in a terminal. main takes the file path as a parameter, which also makes it easy to point at a temporary file:
import builtins
def type_answers(*answers):
queue = iter(answers)
def fake_input(prompt=""):
answer = next(queue)
print(prompt + answer)
return answer
builtins.input = fake_input
MENU = """
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit"""
def main(path="contacts.json"):
try:
contacts = load_contacts(path)
except ValueError as error:
print(f"Cannot start: {error}")
return
while True:
print(MENU)
choice = input("Choose 1-5: ").strip()
if choice == "1":
name = input("Name: ")
phone = input("Phone: ")
email = input("Email (optional): ")
try:
add_contact(contacts, name, phone, email)
except ValueError as error:
print("Not added:", error)
else:
save_contacts(path, contacts)
print("Saved.")
elif choice == "2":
matches = find_contacts(contacts, input("Search for: "))
for name, info in sorted(matches.items()):
print(format_contact(name, info))
if not matches:
print("No matches.")
elif choice == "3":
for name, info in sorted(contacts.items()):
print(format_contact(name, info))
if not contacts:
print("The book is empty.")
elif choice == "4":
name = input("Name to delete: ").strip()
if delete_contact(contacts, name):
save_contacts(path, contacts)
print("Deleted.")
else:
print("No such contact.")
elif choice == "5":
print("Goodbye!")
break
else:
print("Please choose a number from 1 to 5.")
session_file = Path(workdir.name) / "session.json"
type_answers(
"1", "Daniel Kim", "555-0104", "daniel@example.com",
"1", "Elena Rossi", "555-0105", "",
"1", "Daniel Kim", "555-0000", "",
"3",
"2", "ele",
"4", "Daniel Kim",
"9",
"5",
)
main(session_file)
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 1
Name: Daniel Kim
Phone: 555-0104
Email (optional): daniel@example.com
Saved.
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 1
Name: Elena Rossi
Phone: 555-0105
Email (optional):
Saved.
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 1
Name: Daniel Kim
Phone: 555-0000
Email (optional):
Not added: Daniel Kim is already in the book
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 3
Daniel Kim: 555-0104 (daniel@example.com)
Elena Rossi: 555-0105
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 2
Search for: ele
Elena Rossi: 555-0105
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 4
Name to delete: Daniel Kim
Deleted.
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 9
Please choose a number from 1 to 5.
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 5
Goodbye!Follow the session through. Two contacts are added, and the third attempt is refused because Daniel Kim already exists. The list shows both, the search for ele finds Elena, the delete removes Daniel, and 9 is not a valid choice. Notice that save_contacts is called right after each change, so a crash later would not lose the data.
Finally, prove that the data really lives in the file by starting the program again with a fresh run that only lists and quits:
type_answers("3", "5")
main(session_file)
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 3
Elena Rossi: 555-0105
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit
Choose 1-5: 5
Goodbye!Elena is still there, even though this was a brand new call to main. That is persistence.
The complete program
Save this as contacts.py. It is the finished program: the functions from steps 1 and 2, the menu from step 3 and a start line. It reads real input and keeps its data in contacts.json in the folder you run it from:
import json
from pathlib import Path
def add_contact(contacts, name, phone, email=""):
name = name.strip()
if not name:
raise ValueError("a contact needs a name")
if name in contacts:
raise ValueError(f"{name} is already in the book")
contacts[name] = {"phone": phone.strip(), "email": email.strip()}
def find_contacts(contacts, text):
text = text.strip().lower()
return {name: info for name, info in contacts.items() if text in name.lower()}
def delete_contact(contacts, name):
return contacts.pop(name, None) is not None
def format_contact(name, info):
line = f"{name}: {info['phone']}"
if info["email"]:
line += f" ({info['email']})"
return line
def load_contacts(path):
path = Path(path)
if not path.exists():
return {}
try:
with path.open(encoding="utf-8") as file:
return json.load(file)
except json.JSONDecodeError:
raise ValueError(f"{path.name} is not valid JSON")
def save_contacts(path, contacts):
with Path(path).open("w", encoding="utf-8") as file:
json.dump(contacts, file, indent=2, sort_keys=True)
MENU = """
1) Add a contact
2) Search
3) List all
4) Delete
5) Quit"""
def main(path="contacts.json"):
try:
contacts = load_contacts(path)
except ValueError as error:
print(f"Cannot start: {error}")
return
while True:
print(MENU)
choice = input("Choose 1-5: ").strip()
if choice == "1":
name = input("Name: ")
phone = input("Phone: ")
email = input("Email (optional): ")
try:
add_contact(contacts, name, phone, email)
except ValueError as error:
print("Not added:", error)
else:
save_contacts(path, contacts)
print("Saved.")
elif choice == "2":
matches = find_contacts(contacts, input("Search for: "))
for name, info in sorted(matches.items()):
print(format_contact(name, info))
if not matches:
print("No matches.")
elif choice == "3":
for name, info in sorted(contacts.items()):
print(format_contact(name, info))
if not contacts:
print("The book is empty.")
elif choice == "4":
name = input("Name to delete: ").strip()
if delete_contact(contacts, name):
save_contacts(path, contacts)
print("Deleted.")
else:
print("No such contact.")
elif choice == "5":
print("Goodbye!")
break
else:
print("Please choose a number from 1 to 5.")
if __name__ == "__main__":
main()python3 contacts.pyThe file contacts.json appears in the folder after you add the first contact. It is ordinary text, so you can open it in an editor to look, but avoid editing it by hand while the program is running.
Testing it
Because the data functions take their inputs as parameters, tests are short. The file tests use a temporary directory, which Python deletes afterwards. In a separate test file you would write from contacts import ... at the top and finish with unittest.main():
import unittest
class ContactTests(unittest.TestCase):
def test_add_and_find(self):
contacts = {}
add_contact(contacts, "Grace Okafor", "555-0106")
self.assertIn("Grace Okafor", find_contacts(contacts, "grace"))
def test_duplicate_is_rejected(self):
contacts = {}
add_contact(contacts, "Hiro Tanaka", "555-0107")
with self.assertRaises(ValueError):
add_contact(contacts, "Hiro Tanaka", "555-0108")
def test_delete(self):
contacts = {"Isabel Santos": {"phone": "555-0109", "email": ""}}
self.assertTrue(delete_contact(contacts, "Isabel Santos"))
self.assertFalse(delete_contact(contacts, "Isabel Santos"))
def test_save_and_load_round_trip(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "test.json"
original = {"Jack Miller": {"phone": "555-0110", "email": "jack@example.com"}}
save_contacts(path, original)
self.assertEqual(load_contacts(path), original)
def test_missing_file_gives_empty_book(self):
with tempfile.TemporaryDirectory() as folder:
self.assertEqual(load_contacts(Path(folder) / "none.json"), {})
unittest.main(argv=["ignored"], exit=False).....
----------------------------------------------------------------------
Ran 5 tests in 0.001s
OKThe time will differ on your machine. Five passing tests give you confidence to change the program later, such as adding an "edit" option, and to see straight away if you broke something.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Saving only when quitting. If the program crashes first, everything typed is lost. Save after every change.
- Not handling a missing file. On the first run there is no
contacts.json, and a bareopen()would crash. - Overwriting the file when loading fails. If the JSON is damaged, stop and report it, as
maindoes. Carrying on with an empty book and saving would destroy the old data. - Forgetting that JSON keys are strings. Names work perfectly, but a number used as a key would come back as text after a save and load.
- Mixing menu printing with the data logic. Keeping the functions free of
inputandprintis what made the tests possible.
Exercise
Add an update_phone(contacts, name, new_phone) function that changes the phone number of an existing contact and returns True, or returns False if the name is not in the book. Try it on a small dictionary and print the results.
Show one possible answer
def update_phone(contacts, name, new_phone):
if name not in contacts:
return False
contacts[name]["phone"] = new_phone.strip()
return True
demo = {"Asha Verma": {"phone": "555-0101", "email": ""}}
print(update_phone(demo, "Asha Verma", "555-7777"))
print(demo["Asha Verma"]["phone"])
print(update_phone(demo, "Nobody", "555-0000"))True
555-7777
FalseTo offer it in the menu, add a sixth choice that asks for the name and number, calls update_phone, then calls save_contacts.
Ideas to extend it
Store extra details such as a city, sort the list by a different field, or export all contacts to a CSV file. Write each new rule as a function with a test first, then connect it to the menu.
Key points
- Contacts are stored in a dictionary that maps a name to a small dictionary of details, which is a natural fit for JSON.
- json.dump writes the dictionary to a file and json.load reads it back, so the data survives after the program ends.
- Small functions that take the data as a parameter, such as add_contact and find_contacts, are easy to test.
- A menu loop reads a choice, calls the right function and repeats until the user quits.
- The examples here use a temporary folder so that no real files are touched. Your own program will create contacts.json next to your script.
Check yourself
Final exam and certificate
Finish all 70 lessons to unlock a 15-question exam on Python Tutorial. Pass it and you get a certificate with a public link you can share.
Sign in to take the exam