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)returnstrueorfalseand fillsscore. When the key is missing,scoreis set to0, the default forint.scores.ContainsKey(name) ? scores[name] : 0checks first, then reads.
The lesson uses the first one, the shortest.
Step by step
- Look up
nameinscores. - If the key exists,
GetValueOrDefaultreturns the stored score. - If it doesn't, it returns the second argument,
0. - Return the result. A single
returncovers both cases, so there is noifand 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
TryGetValueorContainsKey.
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.
