Introduction

Welcome! Today, we will explore creating a simple address book application using Python dictionaries. This task will help you understand manipulating dictionaries in Python, focusing on adding, retrieving, and deleting entries. By the end of this lesson, you'll have a solid grasp of these fundamental operations.

Introducing Methods to Implement

In this task, we will implement three methods to manage our address book:

  • add_contact(self, name: str, phone_number: str) -> bool: Adds a new contact. Returns False if the contact already exists, otherwise adds the contact and returns True. In this task, let's assume phone numbers do not change, so it's not allowed to overwrite the existing contact's number.
  • get_contact(self, name: str) -> str | None: Retrieves the phone number for a given name. Returns None if the contact does not exist.
  • delete_contact(self, name: str) -> bool: Deletes a contact with the given name. Returns True if the contact exists and is deleted, False otherwise.

Let's break down each method in detail in the next sections.

Step 1: Implementing 'add_contact'

This method adds a new contact to the address book with the given name and phone_number. If the contact already exists, it returns False. Otherwise, it adds the contact and returns True.

Question: Why do you think we need to check if the contact already exists?

Answer: To avoid duplicating existing entries. If a contact with the same name already exists, we shouldn't allow overwriting its phone number in this method, as it's only for creation.

Here is the method implementation:

Python
class AddressBook:
    def __init__(self):
        self.contacts = {}
    
    def add_contact(self, name: str, phone_number: str) -> bool:
        if name in self.contacts:
            return False
        self.contacts[name] = phone_number
        return True

# Example usage:
address_book = AddressBook()
print(address_book.add_contact("Alice", "123-456-7890"))  # True
print(address_book.add_contact("Alice", "098-765-4321"))  # False
print(address_book.contacts)  # {'Alice': '123-456-7890'}

In this method:

  • We verify if the contact already exists using if name in self.contacts.
  • If it exists, we return False.
  • If it doesn't exist, we add it to our dictionary and return True.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal