Start learning free

LESSON 125 OF 674 · DICTIONARIES

Accessing Dictionary Values in C#

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check