Start learning free

LESSON 132 OF 289 · DICTIONARIES - CHALLENGES

Safe Lookup in C#: GetValueOrDefault on a Dictionary

Practice Read the full explanation

Given a Dictionary 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

    C# · DICTIONARIES - CHALLENGES

    Safe Lookup in C#, explained

    Problem overview

    SafeLookup receives scores, a Dictionary<string, int> from names to scores, and a name. It returns the score of name, or 0 when name isn't a key.

    With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and "Dan" gives 0. An empty dictionary has no keys, so every name gives 0. Names must match exactly: "ana" is not "Ana", so it gives 0 too.

    Approach

    The plain indexer, scores[name], throws a KeyNotFoundException for a missing key. That would crash on every name that has no score. You need a read that has an answer ready for missing keys. There are three common ways to write that:

    • scores.GetValueOrDefault(name, 0) returns the value, or the second argument when the key is missing.
    • scores.TryGetValue(name, out int score) returns true or false and fills score. When the key is missing, score is set to 0, the default for int.
    • scores.ContainsKey(name) ? scores[name] : 0 checks first, then reads.

    The lesson uses the first one, the shortest.

    Step by step

    1. Look up name in scores.
    2. If the key exists, GetValueOrDefault returns the stored score.
    3. If it doesn't, it returns the second argument, 0.
    4. Return the result. A single return covers both cases, so there is no if and no exception to catch.

    The solution in C#

    class Solution {
        public int SafeLookup(Dictionary<string, int> scores, string name) {
            return scores.GetValueOrDefault(name, 0);
        }
    }

    The second argument is the fallback and can be any int. Passing 0 says what the lesson wants: no score means 0. If you leave it out, GetValueOrDefault(name) falls back to the default for the value type, which for int is also 0. Spelling the 0 out makes the intent clear.

    Which of the three to choose

    For a single fallback value, GetValueOrDefault is the shortest and reads best. TryGetValue is the one to use when the code must do different things in the two cases, because it gives you the bool as well as the value. The ContainsKey version looks the key up twice when the key exists, once to check and once to read, so it is the least tidy of the three. All of them return the same answers for this lesson, and none of them add the missing key to the dictionary: a lookup never changes the dictionary.

    Edge cases and common mistakes

    • Using the indexer. scores[name] works for names that exist and throws for the rest.
    • Case. Keys are compared exactly, so "ana" and "Ana" are different keys.
    • An empty dictionary. No special case is needed: the lookup simply finds nothing and returns 0.
    • A stored 0. A real score of 0 and a missing key both give 0 here. If you ever need to tell them apart, use TryGetValue or ContainsKey.

    Using it in your own program

    In a file of your own, add using System.Collections.Generic;: GetValueOrDefault for a Dictionary comes from that namespace. It is available in current .NET versions such as .NET 8.

    Testing

    With scores = {"Ana": 90, "Ben": 75, "Cara": 88}, the solution returns 75 for "Ben", 0 for "Dan" and 0 for "ana". With an empty dictionary, "Ana" gives 0.

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free