C#
Dictionary<K,V>
Learn to store key-value pairs with Dictionary<K,V>.
Dictionary<K,V>
Dictionary<K,V> is a collection that stores key-value pairs. Each key is unique; you cannot add the same key twice. The type parameters <string, int> specify the key and value types.
To declare one, write new Dictionary<string, int>(). To add a pair, call the Add method: ages.Add("Ayşe", 30);. To read a value, use the indexer: ages["Ayşe"].
Indexer and initializer
To update the value of a key, use the indexer with assignment: ages["Ayşe"] = 31;. If the key exists, the value is updated; if not, a new pair is added.
To give pairs at declaration, use a collection initializer: new Dictionary<string, int>() { ["a"] = 1, ["b"] = 2 }. Each square bracket is a key and the equals sign assigns its value.
Exercise Add student grades
Declare Dictionary<string, int> grades = new Dictionary<string, int>();. Use Add to put 85 under the key "Ayşe" and 90 under "Alex". Then print grades["Ayşe"] with Console.WriteLine.
Show example solution
First call grades.Add("Ayşe", 85); and grades.Add("Alex", 90);, then print with Console.WriteLine(grades["Ayşe"]);.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare grades dictionary, add two students and print Ayşe's grade
Dictionary<string, int> grades = new Dictionary<string, int>();
grades.Add("Ayşe", 85);
grades.Add("Alex", 90);
Console.WriteLine(grades["Ayşe"]);
}
}
Test yourself
-
Match each expression to its meaning
- Add(key, val)
- Adds a pair
- dict[key]
- Reads value
- dict.Count
- Pair count
- Dictionary<K,V>
- Key-value
-
What does ages["Ayşe"] print?
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Ayşe", 30);
Console.WriteLine(ages["Ayşe"]);
Show answer
30 — Correct. ages["Ayşe"] gives the value of the key, which is 30.
-
Add with the indexer
Dictionary<string, int> ages = new Dictionary<string, int>();
____
Console.WriteLine(ages["Alex"]);
Show answer
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alex"] = 25;
Console.WriteLine(ages["Alex"]);
Next lesson: Dictionary access