Start learning free

LESSON 133 OF 285 · DICTIONARIES - CHALLENGES

Safe Lookup in Go: The Comma-ok Map Check

Practice Read the full explanation

Given a map 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 2
    Ctrl + Enter to check

    GO · DICTIONARIES - CHALLENGES

    Safe Lookup in Go, explained

    Problem overview

    The function safeLookup receives scores, a map[string]int from names to scores, and a name. It returns the score of name, or 0 when name isn't a key. The map may be empty, and keys match exactly, so "ana" is not "Ana".

    With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and "Dan" gives 0. With an empty map, any name gives 0.

    Approach

    A plain scores[name] already returns 0 for a missing key, because Go gives the zero value of the value type, and the zero value of int is 0. That alone would pass here, but it can't tell a missing name from a name whose score really is 0. Go answers that with a two-value lookup:

    score, ok := scores[name]
    

    ok is a bool: true if name is a key, false if not. For "Dan" in the map above, score is 0 and ok is false. For a key stored with the value 0, such as "Zoe" in {"Zoe": 0}, score is 0 and ok is true.

    Step by step

    1. Look up and test in one if. Go lets an if start with a short statement, so if score, ok := scores[name]; ok does the lookup and checks ok. Inside the block, return score.
    2. Return 0 after the if. Execution only gets there when the name wasn't found, because the return inside the block has already ended the function otherwise.

    The solution in Go

    func safeLookup(scores map[string]int, name string) int {
        if score, ok := scores[name]; ok {
            return score
        }
        return 0
    }
    

    Notes on the Go details:

    • Scope. score and ok exist only inside the if statement. That keeps them from leaking into the rest of the function.
    • Unused variables are errors. Both are used, ok in the condition and score in the return. If you only needed to know whether a key exists, write _, ok := scores[name].
    • Why the check is better than the shortcut. The explicit check spells out the intent, and the default can be anything: replacing return 0 with return -1 changes the missing-key answer without touching the lookup. The shortcut can only produce the zero value.

    The two-value form works with any value type, which is where it matters. For a map[string]string, the zero value is the empty string, and for a map[string]bool it is false. If a name could really have the score 0, the check is the only way to tell "not in the map" from "stored as 0". Here the scores are between 0 and 100, so a stored 0 and a missing name both give 0 and the check changes nothing in the result.

    Edge cases and common mistakes

    • Empty map. A lookup in {} is fine: ok is false and the function returns 0.
    • Case sensitivity. safeLookup(scores, "ana") returns 0 when only "Ana" is a key.
    • Returning inside the wrong place. Putting return 0 inside the if block would return 0 for every name that exists.

    Testing

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