Start learning free

LESSON 129 OF 287 · DICTIONARIES - CHALLENGES

Phone Book Lookup in Python: Reading a Dictionary Value

Practice Read the full explanation

Given a phone book phoneBook, a dict from names to phone numbers, and a name, return the phone number of name.

Every name in the phone book is a key, and its value is that person's phone number, a string like "555-0142". The name you look up is always in the phone book.

 

Example 1:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"}, name = "Ben"
Output: "555-0199"
Explanation: The key "Ben" maps to "555-0199".

Example 2:

Input: phoneBook = {"Max": "555-0100"}, name = "Max"
Output: "555-0100"
Explanation: The phone book has a single entry, and it is the one we look up.

Example 3:

Input: phoneBook = {"Tom": "555-0111", "Tim": "555-0111"}, name = "Tim"
Output: "555-0111"
Explanation: Tom and Tim share a phone number. We only need the value of the key "Tim".

 

Constraints:

  • phoneBook has at least one entry.
  • name is always a key of phoneBook.
  • Names are single words made of English letters, and they are all different. Two people can share a phone number.
  • Every phone number is a string of three digits, a dash and four digits, like "555-0142".
STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · DICTIONARIES - CHALLENGES

    Phone Book Lookup in Python, explained

    Problem overview

    The function phoneBookLookup receives a dictionary, phoneBook, that maps names to phone numbers, and a name. It returns that person's number. The name is always a key of the dictionary, so there is no missing case to handle.

    For {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"} and name = "Ben", the answer is "555-0199".

    Approach

    A dictionary stores key and value pairs. You give it a key and it gives back the value stored under it, without looping through the entries. The syntax is the same square brackets that a list uses, but the thing inside is a key, not a position: phoneBook["Ben"].

    In this lesson the key is held in the parameter name, so the lookup is phoneBook[name].

    Compare this with a list of pairs. To find Ben in a list you would check the entries one by one until you met him, and a longer list would take longer. A dictionary finds the key directly: on average the time doesn't grow with the number of entries. That speed is the reason to reach for a dictionary whenever data comes as "find the thing that goes with this name".

    A few related tools are handy when you work with a dictionary like this. The test "Ana" in phoneBook is True when the key exists and False otherwise, and "Zed" in phoneBook is False for a name that isn't there. The method keys() lists the names, values() lists the numbers, and for name, number in phoneBook.items() loops over both together. This lesson needs none of them, only the single lookup.

    Step by step

    1. Index the dictionary with name and return the result. One expression does the whole job.

    The solution in Python

    class Solution:
        def phoneBookLookup(self, phoneBook: Dict[str, str], name: str) -> str:
            return phoneBook[name]
    

    Details worth knowing:

    • A variable, not a string. phoneBook[name] looks up whatever text name holds. phoneBook["name"] looks up the literal word "name", which is not a key here.
    • A missing key raises KeyError. With the dictionary above, phoneBook["ben"] raises KeyError: 'ben', because keys are matched exactly, capital letters included. This lesson promises the name is present. When a key may be missing, phoneBook.get(name) returns None instead of raising, and phoneBook.get(name, "unknown") returns the default you give it.
    • Shared values are fine. Keys are unique, values are not. With {"Tom": "555-0111", "Tim": "555-0111"}, looking up "Tim" returns "555-0111", and so does "Tom".
    • The value is a string. The number "555-0142" has a dash, so it can't be an integer. It is returned exactly as stored.

    Edge cases and common mistakes

    • Quoting the variable. The most common slip, covered above.
    • Using parentheses. phoneBook(name) tries to call the dictionary like a function and fails. Dictionaries are indexed with square brackets.
    • Single entry. {"Max": "555-0100"} with "Max" returns "555-0100". Nothing special is needed.

    Why the keys are strings

    A dictionary key has to be something that can't change after it is stored, such as a string, a number or a tuple. Names are strings, so they fit naturally, and "Ben" and "ben" are two different keys. A list can't be a key; Python raises TypeError: unhashable type: 'list' when you try.

    Testing

    • {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"} with "Ben" gives 555-0199.
    • {"Tom": "555-0111", "Tim": "555-0111"} with "Tim" gives 555-0111.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free