Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 10 of 10

Time to build something with real structure. A contact book needs to store people, find them by name, update them, and remove them — exactly what a dictionary is for.

The data shape

Each contact has several fields, so each contact is a dictionary. We look contacts up by name, so the whole book is a dictionary too: name maps to contact record.

contacts = {
    "Ada": {"phone": "555-0100", "email": "ada@example.com"},
    "Grace": {"phone": "555-0199", "email": "grace@example.com"},
}

print(contacts["Ada"]["phone"])

A list of dictionaries would also work, but then finding "Ada" means looping through every record. With a dictionary keyed by name, lookup is immediate — this is lesson 3.9 in practice.

The operations

Add or update — same line, because assigning to a key creates or replaces it:

contacts = {}
contacts["Alan"] = {"phone": "555-0142", "email": "alan@example.com"}
print(contacts)

Search, safely:

contacts = {"Ada": {"phone": "555-0100"}}
name = "Grace"

if name in contacts:
    print(contacts[name])
else:
    print(f"{name} not found.")

Update one field without replacing the whole record:

contacts = {"Ada": {"phone": "555-0100", "email": "ada@example.com"}}
contacts["Ada"]["phone"] = "555-0101"
print(contacts["Ada"])

Delete:

contacts = {"Ada": {"phone": "555-0100"}, "Alan": {"phone": "555-0142"}}
del contacts["Alan"]
print(list(contacts.keys()))

List everything, using .items() and unpacking:

contacts = {
    "Ada": {"phone": "555-0100", "email": "ada@example.com"},
    "Grace": {"phone": "555-0199", "email": "grace@example.com"},
}

for name, info in contacts.items():
    print(f"{name}: {info['phone']}")

The full program

Everything above, wired into a menu loop. This uses while True with a sentinel from Module 2, if/elif branching, and every dictionary operation from this module.

contacts = {}

while True:
    print("\n1) Add  2) Find  3) Delete  4) List  5) Quit")
    choice = input("Choose: ")

    if choice == "1":
        name = input("Name: ")
        phone = input("Phone: ")
        email = input("Email: ")
        contacts[name] = {"phone": phone, "email": email}
        print(f"Saved {name}.")

    elif choice == "2":
        name = input("Name to find: ")
        if name in contacts:
            info = contacts[name]
            print(f"{name}: {info['phone']}, {info['email']}")
        else:
            print(f"{name} not found.")

    elif choice == "3":
        name = input("Name to delete: ")
        if name in contacts:
            del contacts[name]
            print(f"Deleted {name}.")
        else:
            print(f"{name} not found.")

    elif choice == "4":
        if not contacts:
            print("Contact book is empty.")
        for name, info in contacts.items():
            print(f"{name}: {info['phone']}")

    elif choice == "5":
        print("Goodbye!")
        break

    else:
        print("Unknown option.")

Two small touches worth noticing: "\n" at the start of the menu prints a blank line to keep things readable, and if not contacts: is the idiomatic way to ask "is this empty?" — an empty dictionary is falsy.

Try it yourself

Run it. Add a couple of contacts, look one up, list them all, delete one, then quit.

Take it further

  • Store multiple phone numbers per contact by making "phones" a list.
  • Add a "tags" set per contact and search by tag.
  • Make search case-insensitive with .lower().
  • Sort the listing alphabetically with sorted(contacts.items()).

One thing you can't do yet: the book empties every time the program stops. Module 6 covers saving to a file so your data survives.

Module 3 complete

You can now store collections of data in the right shape — lists, tuples, dictionaries, and sets, plain or nested — and pick between them deliberately.

Next up: Module 4 — Functions & Scope, where you'll package logic into reusable pieces instead of one long script.

Questions about this lesson

Log in to ask a question.