Start learning free

LESSON 132 OF 673 · DICTIONARIES - CHALLENGES

Safe Lookup in Python: dict.get with a Default

Practice Read the full explanation

Given a dict scores from names to scores and a name, return the score of name, or 0 when name isn't a key of scores.

Some names you look up aren't in the dictionary at all. They have no score, so the answer for them is 0.

 

Example 1:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Ben"
Output: 75
Explanation: "Ben" is a key of scores, and its value is 75.

Example 2:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Dan"
Output: 0
Explanation: "Dan" isn't a key of scores, so the answer is 0.

Example 3:

Input: scores = {}, name = "Ana"
Output: 0
Explanation: An empty dictionary has no keys at all.

 

Constraints:

  • scores can be empty.
  • Names are single words made of English letters, and the names in scores are all different.
  • name matches a key only when it is spelled exactly the same, upper and lower case included: "ana" is not "Ana".
  • Every score is between 0 and 100.
STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · DICTIONARIES - CHALLENGES

    Safe Lookup in Python, explained

    Problem overview

    The function safeLookup receives a dictionary scores that maps names to scores and a name. It returns the score of name, or 0 when name isn't a key. Unlike a plain lookup, this one must work for names that aren't there, and for an empty dictionary.

    With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and "Dan" gives 0. With {} and "Ana" the answer is 0.

    Approach

    The brackets scores[name] raise a KeyError when the key is missing, which would crash the function. One way around it is to test first with if name in scores. The dictionary method get does the test and the lookup in one call: scores.get(name, 0) returns the stored value if the key exists, and the second argument, 0, if it doesn't.

    The longer form is worth seeing, because it spells out what get does:

    def safe(scores, name):
        if name in scores:
            return scores[name]
        return 0
    

    It gives the same answers: 75 for {"Ben": 75} with "Ben", and 0 with "Dan". The get version is shorter and does the key search once instead of twice.

    Step by step

    1. Return scores.get(name, 0). The first argument is the key to look for and the second is the default for a missing key.

    The solution in Python

    class Solution:
        def safeLookup(self, scores: Dict[str, int], name: str) -> int:
            return scores.get(name, 0)
    

    Details worth knowing:

    • The default is optional. scores.get("Dan") with no second argument returns None for a missing key. Here the answer must be 0, so the default is given explicitly.
    • get doesn't change the dictionary. It only reads. The missing key isn't added.
    • Keys match exactly. With the dictionary above, "ana" isn't "Ana", so scores.get("ana", 0) gives 0.
    • A stored 0 and a missing key look the same. With {"Zed": 0}, looking up "Zed" returns 0, because that is the stored score. Here that is fine, since both cases must answer 0. When a missing key must be told apart from a stored value, use in or a default that can't be a real value, such as None.

    Edge cases and common mistakes

    • Square brackets. scores[name] works for "Ben" but raises KeyError for "Dan" and for any name looked up in an empty dictionary.
    • Forgetting the default. scores.get(name) returns None for a missing name, not 0, and the tests expect the number.
    • Parentheses mix-up. scores.get[name, 0] fails: get is a method, so it is called with parentheses.

    Choosing the default

    The default doesn't have to be a number. It is simply what get hands back when the key is missing, so scores.get(name, -1) would answer -1, and scores.get(name, "no score") would answer with that text. The lesson picks 0 because a name without a score counts as zero points, and the scores are all between 0 and 100. The same pattern is common in counting code, where a missing key means "seen zero times so far": counts.get(word, 0) + 1 is the new count.

    For example, counting the words of a list this way, counts[w] = counts.get(w, 0) + 1, turns ["a", "b", "a"] into {'a': 2, 'b': 1}.

    Testing

    • {"Ana": 90, "Ben": 75, "Cara": 88} with "Ben" gives 75.
    • The same dictionary with "Dan" gives 0.
    • The same dictionary with "ana" gives 0.
    • {} with "Ana" gives 0.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free