Codiqo

Learn C# · lesson 30 of 61 · about 8 minutes

Dictionary

Open the bestiary: pair each enemy with its HP in a Dictionary, and look names up safely.

What you'll learn

  • Create a Dictionary<TKey, TValue>
  • Add, change and look up values
  • Check keys safely with ContainsKey and TryGetValue

The bestiary

Before the next fight, the hero opens a bestiary: a book of how much HP each enemy has. One list of names and another of HP would work, but finding the Troll's HP would mean searching both. A Dictionary<string, int> pairs each enemy (the key) with its HP (the value), so bestiary["Troll"] finds it straight away. A new page is added with bestiary["Dragon"] = 60, and TryGetValue looks up a typed name without crashing when there are no notes on it.

Look-up tables

Dictionary<string, int> ages = new() { ["Ada"] = 12 }; maps keys to values.

  • ages["Bo"] = 10; adds or changes
  • ages["Ada"] reads, but throws KeyNotFoundException if the key is missing
  • ages.ContainsKey("Cy") checks first
  • ages.TryGetValue("Cy", out int age) checks and reads in one go
  • foreach (var (name, age) in ages) visits every pair

Stock levels

Dictionary<string, int> stock = new()
{
    ["apples"] = 5,
    ["pears"] = 0,
};
stock["plums"] = 8;
stock["apples"] -= 2;

Console.WriteLine($"{stock["apples"]} apples, {stock.Count} kinds");
Console.WriteLine(stock.ContainsKey("kiwis"));
if (stock.TryGetValue("plums", out int plums)) Console.WriteLine($"{plums} plums");

foreach (var (fruit, count) in stock)
{
    Console.WriteLine($"{fruit}: {count}");
}

Output

3 apples, 3 kinds
False
8 plums
apples: 3
pears: 0
plums: 8

Tip

Keys are compared exactly, capitals included, so "goblin" isn't "Goblin". A key is only ever in a dictionary once: setting it again replaces its value, but Add with a key that's already there throws an ArgumentException.

Tip

A Dictionary doesn't promise any order for its pairs. When the order matters, sort them, for example by key with OrderBy, which you'll meet in this unit.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.