Dictionaries help you store and find data quickly using keys. You use methods to add, check, or get values easily.
Dictionary methods and access patterns in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
C Sharp (C#)
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(); dict.Add(key, value); var value = dict[key]; bool hasKey = dict.ContainsKey(key); dict.TryGetValue(key, out value);
Use Add to insert new key-value pairs.
Use ContainsKey to check if a key exists before accessing it.
Examples
C Sharp (C#)
var dict = new Dictionary<string, int>(); dict.Add("apple", 3); int count = dict["apple"];
C Sharp (C#)
if (dict.ContainsKey("banana")) { Console.WriteLine(dict["banana"]); } else { Console.WriteLine("No banana found"); }
C Sharp (C#)
if (dict.TryGetValue("orange", out int orangeCount)) { Console.WriteLine(orangeCount); } else { Console.WriteLine("No orange found"); }
C Sharp (C#)
foreach (var pair in dict) {
Console.WriteLine($"{pair.Key}: {pair.Value}");
}Sample Program
This program creates a dictionary of fruits and their counts. It shows how to add items, check for keys, safely get values, and loop through all items.
C Sharp (C#)
using System; using System.Collections.Generic; class Program { static void Main() { var fruits = new Dictionary<string, int>(); fruits.Add("apple", 5); fruits.Add("banana", 2); if (fruits.ContainsKey("apple")) { Console.WriteLine($"Apple count: {fruits["apple"]}"); } if (fruits.TryGetValue("orange", out int orangeCount)) { Console.WriteLine($"Orange count: {orangeCount}"); } else { Console.WriteLine("No orange found"); } Console.WriteLine("All fruits:"); foreach (var fruit in fruits) { Console.WriteLine($"{fruit.Key}: {fruit.Value}"); } } }
Important Notes
Accessing a key that does not exist without checking causes an error.
Use TryGetValue to avoid exceptions when unsure if a key exists.
Dictionary keys must be unique; adding a duplicate key causes an error.
Summary
Dictionaries store data with unique keys for fast access.
Use Add, ContainsKey, and TryGetValue to manage dictionary data safely.
Loop through dictionaries with foreach to see all keys and values.
Practice
1. What does the
ContainsKey method do in a C# Dictionary?easy
Solution
Step 1: Understand the purpose of ContainsKey
TheContainsKeymethod checks if a given key is present in the dictionary.Step 2: Compare with other dictionary methods
Addadds items,Removedeletes items, andCountreturns the number of items, so these are different fromContainsKey.Final Answer:
Checks if a specific key exists in the dictionary -> Option AQuick Check:
ContainsKey checks key presence [OK]
Hint: ContainsKey checks if key exists before access [OK]
Common Mistakes:
- Confusing ContainsKey with Add method
- Thinking ContainsKey returns a value instead of a boolean
- Mixing ContainsKey with Count property
2. Which of the following is the correct way to add a key-value pair to a
Dictionary<string, int> named ages?easy
Solution
Step 1: Recall the syntax for adding items to Dictionary
The correct method to add a key-value pair isAdd(key, value).Step 2: Check each option's syntax
ages.Add("Alice", 30); usesAdd("Alice", 30)which is correct. ages.Add["Alice"] = 30; uses square brackets with Add which is invalid. ages["Alice"].Add(30); tries to call Add on the value, which is wrong. ages.Insert("Alice", 30); uses Insert which does not exist for Dictionary.Final Answer:
ages.Add("Alice", 30); -> Option AQuick Check:
Add(key, value) syntax [OK]
Hint: Use Add(key, value) to insert new pairs [OK]
Common Mistakes:
- Using square brackets with Add method
- Trying to call Add on a value instead of dictionary
- Using Insert method which does not exist
3. What will be the output of this code?
var dict = new Dictionary<string, int>();
dict.Add("x", 10);
dict["y"] = 20;
Console.WriteLine(dict["x"] + dict["y"]);medium
Solution
Step 1: Understand dictionary additions
First,dict.Add("x", 10)adds key "x" with value 10. Thendict["y"] = 20adds key "y" with value 20.Step 2: Calculate the sum printed
dict["x"]is 10 anddict["y"]is 20, so their sum is 30.Final Answer:
30 -> Option BQuick Check:
10 + 20 = 30 [OK]
Hint: Sum values accessed by keys with dict[key] syntax [OK]
Common Mistakes:
- Expecting output as separate values instead of sum
- Confusing keys and values in output
- Thinking dict["y"] is invalid without Add
4. Identify the error in this code snippet:
var dict = new Dictionary<string, int>();
dict.Add("a", 1);
dict.Add("a", 2);
Console.WriteLine(dict["a"]);medium
Solution
Step 1: Understand Add method behavior with duplicate keys
TheAddmethod throws an exception if the key already exists.Step 2: Analyze the code flow
The firstAdd("a", 1)works fine. The secondAdd("a", 2)tries to add the same key again, causing an exception.Final Answer:
Duplicate key exception on second Add call -> Option CQuick Check:
Adding duplicate key throws exception [OK]
Hint: Add throws error if key exists; use indexer to overwrite [OK]
Common Mistakes:
- Assuming Add overwrites existing keys
- Expecting no error and value updated
- Confusing Add with indexer assignment
5. Given a dictionary
scores with student names as keys and their scores as values, which code snippet safely retrieves the score for "John" without causing an error if the key is missing?hard
Solution
Step 1: Understand safe retrieval methods
UsingTryGetValuesafely tries to get the value and returns false if key is missing without error.Step 2: Analyze each option
int score = scores["John"]; throws an exception if "John" is missing. int score = scores.GetValueOrDefault("John"); is invalid in C# Dictionary (GetValueOrDefault is not standard). scores.TryGetValue("John", out int score); uses TryGetValue correctly. int score = scores.ContainsKey("John"); returns a boolean, not the score.Final Answer:
scores.TryGetValue("John", out int score); -> Option DQuick Check:
TryGetValue safely gets value [OK]
Hint: Use TryGetValue to avoid errors on missing keys [OK]
Common Mistakes:
- Using indexer without checking key existence
- Confusing ContainsKey with value retrieval
- Expecting GetValueOrDefault method on Dictionary
