Skip to content
Codewilds

Lesson 15 of 34 · Arrays & Lists

C# Dictionary<TKey, TValue>

medium20 XP2 min read

How many potions are left? What does a sword cost? Which player owns this save file? Questions like these are about looking things up by a key. Searching a list from start to finish works, but gets slow as the list grows. A Dictionary<TKey, TValue> finds a value by its key almost instantly, no matter how many entries it holds.

Creating a dictionary

A dictionary maps keys to values. Both types are given in angle brackets:

var prices = new Dictionary<string, decimal>
{
    ["sword"] = 120m,
    ["shield"] = 85m,
};
var ages = new Dictionary<string, int>();   // empty

Keys are unique: one key, one value. Values can repeat.

Adding, reading and updating

prices["potion"] = 12.5m;          // add (or overwrite if the key exists)
prices["sword"] = 110m;            // update
Console.WriteLine(prices["shield"]); // 85
Console.WriteLine(prices.Count);   // 3

prices.Add("bow", 60m);            // Add throws if "bow" already exists
prices.Remove("potion");           // returns true if the key was there

Reading a key that does not exist with prices["axe"] throws a KeyNotFoundException. Check first, or use TryGetValue, which works like int.TryParse:

if (prices.ContainsKey("axe")) { /* ... */ }

if (prices.TryGetValue("bow", out decimal bowPrice))
{
    Console.WriteLine($"A bow costs {bowPrice}");
}

decimal axe = prices.GetValueOrDefault("axe");   // 0 when missing

Looping over a dictionary

Each entry is a KeyValuePair<TKey, TValue> with .Key and .Value. You can also deconstruct it into two variables:

foreach (KeyValuePair<string, decimal> entry in prices)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

foreach (var (item, price) in prices)
{
    Console.WriteLine($"{item} costs {price}");
}

prices.Keys and prices.Values give you just the keys or just the values. Do not rely on the order of a dictionary — when you need sorted output, sort the keys yourself.

The counting pattern

Counting how often things occur is the classic dictionary job:

string[] drops = { "gem", "coin", "gem", "gem", "coin" };
var counts = new Dictionary<string, int>();
foreach (string drop in drops)
{
    if (counts.ContainsKey(drop))
        counts[drop]++;
    else
        counts[drop] = 1;
}
// counts: gem → 3, coin → 2

counts[drop] = counts.GetValueOrDefault(drop) + 1; does the same thing in one line.

Choosing keys

Keys are compared with their Equals method, so string keys are case-sensitive: "Sword" and "sword" are different keys. Normalise text (for example with ToLower()) before using it as a key, or create the dictionary with new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase).

Common mistakes

  • Reading a missing key with dict[key] — use TryGetValue or ContainsKey.
  • Calling Add for a key that already exists — use the indexer to overwrite.
  • Changing the dictionary inside a foreach over it — just like lists, that throws.

Assignment

Complete three methods in Program:

  1. WordCounts(text) returns how often each word appears. Words are separated by spaces (ignore extra spaces) and counted case-insensitively using lowercase keys: WordCounts("The cat the hat") has the → 2, cat → 1, hat → 1.
  2. PriceOf(prices, item) returns the price of item, or -1 when the item is not for sale.
  3. MostExpensive(prices) returns the name of the most expensive item, or "" for an empty dictionary.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Maps and dictionaries in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Lesson 15 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.