In C#, you access values in a Dictionary by indexing it with the key, dict[key]:
Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Alice"] = 95;
scores["Bob"] = 87;
int aliceScore = scores["Alice"]; // 95
int bobScore = scores["Bob"]; // 87
If the key doesn't exist, the indexer throws a KeyNotFoundException. Use GetValueOrDefault() to provide a fallback:
int score = scores.GetValueOrDefault("Diana", 0); // returns 0 if not found
Check if a key exists with ContainsKey():
if (scores.ContainsKey("Alice")) {
Console.WriteLine(scores["Alice"]);
}
Assignment
Follow the Coding Tutorial and access Alice's score from scores!
Hint
Use scores["Alice"] and assign it to aliceScore.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
