Now that we have the basic structure of our contact book application – adding contacts – it's time to make it more robust by adding the essential features of editing, deleting, and persisting our data. This will make our application much more practical and user-friendly.
We'll start by tackling the deletion feature. Deleting a contact involves finding a specific contact and removing it from our list. To do this, we'll need a way for the user to specify which contact to delete. A common approach is to ask for the contact's name. We'll then iterate through our contacts, find the matching one, and remove it. It's important to handle cases where the contact might not exist to avoid errors.
def delete_contact(contacts, name):
for i, contact in enumerate(contacts):
if contact['name'].lower() == name.lower():
del contacts[i]
print(f"'{name}' has been deleted.")
return
print(f"Contact '{name}' not found.")Next, let's add the editing functionality. Editing a contact is similar to deleting, in that we first need to find the contact. Once found, we'll allow the user to update the details (like phone number or email) for that specific contact. This often involves asking for the new information after confirming the contact to be edited.
def edit_contact(contacts, name):
for contact in contacts:
if contact['name'].lower() == name.lower():
print(f"Editing contact: {contact['name']}")
new_phone = input("Enter new phone number (leave blank to keep current): ")
if new_phone:
contact['phone'] = new_phone
new_email = input("Enter new email (leave blank to keep current): ")
if new_email:
contact['email'] = new_email
print("Contact updated successfully.")
return
print(f"Contact '{name}' not found.")Now, for the crucial part: saving and loading our contacts. Without this, all our hard work would be lost every time the program closes. We'll use Python's built-in json module for this. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. We can save our list of dictionaries directly to a JSON file and load it back when the application starts.