C# Dictionary
Dictionary
In a List, you find an item by its index: 0, 1, 2 and so on. But sometimes a number is not a good way to find a value.
Think of a phone book. You don't look for "person number 37". You look for a name, and you find the phone number next to it.
A Dictionary works the same way. It stores items in pairs: a key (like the name) and a value (like the phone number). You use the key to find the value.
Like List, Dictionary is in the System.Collections.Generic namespace:
Example
// Include the namespace that holds Dictionary
using System.Collections.Generic;
Create a Dictionary
This example creates a dictionary where each key is a country, and each value is the capital city of that country:
Example
Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals.Add("Norway", "Oslo");
capitals.Add("Japan", "Tokyo");
capitals.Add("Germany", "Berlin");
Console.WriteLine(capitals["Japan"]); // Tokyo
Example explained
- In
Dictionary<string, string>, the first type is the type of the keys, and the second type is the type of the values. Here, both are strings. Add()adds a key and its value.capitals["Japan"]reads the value of the key "Japan".
Each key can only be in a dictionary once. If you Add() a key that is already there, you get an error.
You can also add the pairs when you create the dictionary. Put each pair inside its own curly braces { }:
Example
Dictionary<string, string> capitals = new Dictionary<string, string>
{
{ "Norway", "Oslo" },
{ "Japan", "Tokyo" },
{ "Germany", "Berlin" }
};
Console.WriteLine(capitals["Norway"]); // Oslo
Change and Remove Items
The keys and the values can have different types. In this dictionary, the keys are names (string) and the values are ages (int).
To change a value, write the key inside [ ] and give it a new value:
Example
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Liam", 30);
ages.Add("Jenny", 25);
ages["Liam"] = 31;
Console.WriteLine(ages["Liam"]); // 31
To remove a pair, use Remove() with the key. Count tells you how many pairs the dictionary has:
Example
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Liam", 30);
ages.Add("Jenny", 25);
ages.Add("Angie", 28);
ages.Remove("Jenny");
Console.WriteLine(ages.Count); // 2
Loop Through a Dictionary
Use a foreach loop to go through all the pairs. Each pair is a KeyValuePair, with a Key and a Value:
Example
Dictionary<string, string> capitals = new Dictionary<string, string>
{
{ "Norway", "Oslo" },
{ "Japan", "Tokyo" },
{ "Germany", "Berlin" }
};
foreach (KeyValuePair<string, string> item in capitals)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
The types inside KeyValuePair<string, string> are the same as the types of the dictionary.
Check If a Key Exists
If you read a key that does not exist, like capitals["Spain"], the program stops with an error (a KeyNotFoundException).
To avoid this, check the key first with ContainsKey(). It returns true if the key exists, and false if it does not:
Example
Dictionary<string, string> capitals = new Dictionary<string, string>
{
{ "Norway", "Oslo" },
{ "Japan", "Tokyo" },
{ "Germany", "Berlin" }
};
if (capitals.ContainsKey("Spain"))
{
Console.WriteLine(capitals["Spain"]);
}
else
{
Console.WriteLine("Spain is not in the dictionary");
}
TryGetValue() checks the key and reads the value in one step. It works like int.TryParse(), which you learned about in ref and out:
- It returns
trueif the key exists, andfalseif not. - It puts the value in the
outvariable.
Example
Dictionary<string, string> capitals = new Dictionary<string, string>
{
{ "Norway", "Oslo" },
{ "Japan", "Tokyo" },
{ "Germany", "Berlin" }
};
if (capitals.TryGetValue("Japan", out string capital))
{
Console.WriteLine("The capital of Japan is " + capital);
}