Python - 28
Python - 28: Building a Contact Manager
Let's combine lists, dictionaries, loops, and functions to build a simple contact manager.
Your challenge: Add contacts to a list, display them, and search for one contact by name.
Store contacts as dictionaries
Each contact can be a dictionary with keys such as "name" and "phone".
Keep contacts in a list
The add_contact() function creates a dictionary and adds it to the contacts list with append().
Display the contacts
Loop through the list and access each value with its key: contact["name"]
Search by name
Loop through the contacts again and compare each name with search_name.
Try it: Change search_name and add another fictional contact to the list.
Good Python habit: Use a dictionary when several related values belong to one item, then use a list when you need to store many of those items.
👀 Show Example Solution
contacts = []
def add_contact(name, phone):
contact = {
"name": name,
"phone": phone
}
contacts.append(contact)
add_contact("Alex", "555-1234")
add_contact("Sam", "555-9876")
add_contact("Taylor", "555-5555")
print("Contact List:")
for contact in contacts:
print("Name:")
print(contact["name"])
print("Phone:")
print(contact["phone"])
print("---")
search_name = "Sam"
print("Searching for:")
print(search_name)
for contact in contacts:
if contact["name"] == search_name:
print("Contact Found!")
print(contact["phone"])Each contact is stored as a dictionary, all contacts are kept in one list, and loops make it easy to display and search them.
