Challenge - 5 Problems
Dictionary Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing dictionary with TryGetValue
What is the output of this C# code snippet?
C Sharp (C#)
var dict = new Dictionary<string, int> { {"apple", 3}, {"banana", 5} }; if (dict.TryGetValue("banana", out int value)) { Console.WriteLine(value); } else { Console.WriteLine("Not found"); }
Attempts:
2 left
💡 Hint
TryGetValue returns true if the key exists and outputs the value.
✗ Incorrect
The key "banana" exists with value 5, so TryGetValue returns true and prints 5.
❓ Predict Output
intermediate2:00remaining
Result of removing a key from dictionary
What is the output of this C# code?
C Sharp (C#)
var dict = new Dictionary<int, string> { {1, "one"}, {2, "two"} }; bool removed = dict.Remove(3); Console.WriteLine(removed);
Attempts:
2 left
💡 Hint
Remove returns false if the key does not exist.
✗ Incorrect
Key 3 does not exist, so Remove returns false and prints False.
❓ Predict Output
advanced2:00remaining
Output of dictionary indexer with missing key
What happens when this C# code runs?
C Sharp (C#)
var dict = new Dictionary<string, int> { {"x", 10} }; Console.WriteLine(dict["y"]);
Attempts:
2 left
💡 Hint
Accessing a missing key with indexer throws an exception.
✗ Incorrect
The key "y" does not exist, so accessing dict["y"] throws KeyNotFoundException.
❓ Predict Output
advanced2:00remaining
Count of items after TryAdd calls
What is the count of items in the dictionary after this code runs?
C Sharp (C#)
var dict = new Dictionary<int, string>(); dict.TryAdd(1, "one"); dict.TryAdd(1, "uno"); dict.TryAdd(2, "two"); Console.WriteLine(dict.Count);
Attempts:
2 left
💡 Hint
TryAdd does not overwrite existing keys.
✗ Incorrect
The second TryAdd with key 1 fails, so only keys 1 and 2 exist, count is 2.
❓ Predict Output
expert2:00remaining
Output of iterating dictionary keys and values
What is the output of this C# code?
C Sharp (C#)
var dict = new Dictionary<string, int> { {"a", 1}, {"b", 2} }; foreach (var key in dict.Keys) { Console.Write(key); } foreach (var value in dict.Values) { Console.Write(value); }
Attempts:
2 left
💡 Hint
Keys and values are iterated in the same order as insertion.
✗ Incorrect
Keys are "a", "b" and values are 1, 2, so output is "ab12".