Practice: Phone Book

Practice: Phone Book

This exercise combines dictionary updates, get, and functions that share one dictionary.

Exercise

  1. Define a function named add_contact with three parameters: book (a dictionary), name, and number. It stores the number under the name — adding or replacing — and returns nothing.
  2. Define a function named lookup with two parameters: book and name. It returns the stored number, or the string "unknown" when the name is not in the book.
  3. Define a function named contact_count with one parameter, book. It returns the number of contacts.
book = {}
add_contact(book, "Ada", "555-0101")
print(lookup(book, "Ada"))
print(lookup(book, "Grace"))

Output:

555-0101
unknown

Run your code to see the output, then press Submit.

Hints

  • add_contact is one assignment; it needs no return.
  • lookup is a single get with a fallback.

Tests

import unittest


class TestPhoneBook(unittest.TestCase):
    def test_added_contact_can_be_looked_up(self):
        book = {}
        add_contact(book, "Ada", "555-0101")
        self.assertEqual(lookup(book, "Ada"), "555-0101")

    def test_missing_contact_is_unknown(self):
        self.assertEqual(lookup({}, "Grace"), "unknown")

    def test_adding_again_replaces_the_number(self):
        book = {"Ada": "555-0101"}
        add_contact(book, "Ada", "555-0202")
        self.assertEqual(lookup(book, "Ada"), "555-0202")

    def test_contact_count(self):
        book = {}
        add_contact(book, "Ada", "1")
        add_contact(book, "Grace", "2")
        self.assertEqual(contact_count(book), 2)
def add_contact(book, name, number):
    book[name] = number


def lookup(book, name):
    return book.get(name, "unknown")


def contact_count(book):
    return len(book)


book = {}
add_contact(book, "Ada", "555-0101")
print(lookup(book, "Ada"))
print(lookup(book, "Grace"))
print(contact_count(book))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.