0Pricing
C# Academy · Lesson

Dictionary Lookups

Fast key-value access.

Dictionary Lookups is a free C# Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Key-Value Pairs

Dictionary<TKey, TValue> maps unique keys to values. Think of it as a lookup table: give it a key, get the value back fast.

It is backed by a hash table, so finding a value by key is on average O(1), far faster than scanning a list.

using System.Collections.Generic;

var ages = new Dictionary<string, int>();
ages["Ann"] = 30;
ages["Bob"] = 25;

Initializing a Dictionary

You can seed a dictionary with a collection initializer. Each entry pairs a key with its value.

Keys must be unique. Supplying the same key twice in an initializer throws an ArgumentException at runtime.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var caps = new Dictionary<string, string> {
            ["FR"] = "Paris",
            ["JP"] = "Tokyo"
        };
        Console.WriteLine(caps["JP"]);
    }
}

Reading by Key

Use the indexer to read: dict[key]. This is O(1) on average.

But beware: if the key is missing, the indexer throws KeyNotFoundException. Reading an absent key is one of the most common dictionary bugs.

var ages = new Dictionary<string, int> { ["Ann"] = 30 };
int a = ages["Ann"];      // 30
// int b = ages["Zoe"];   // throws KeyNotFoundException

Safe Lookup with TryGetValue

TryGetValue avoids exceptions. It returns true and sets an out variable when the key exists, or false otherwise.

This is the idiomatic, allocation-free way to look up a value you are unsure about.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var ages = new Dictionary<string, int> { ["Ann"] = 30 };
        if (ages.TryGetValue("Ann", out int v))
            Console.WriteLine(v);
    }
}

ContainsKey and Defaults

ContainsKey checks for a key without reading the value, in O(1). Use it before an indexer read when you only need a yes or no.

If you call both ContainsKey and the indexer, you hash the key twice. TryGetValue does it once, so it is usually faster.

var ages = new Dictionary<string, int> { ["Ann"] = 30 };
if (ages.ContainsKey("Ann"))
    System.Console.WriteLine(ages["Ann"]);

Adding vs Assigning

The indexer dict[key] = value inserts a new pair or overwrites an existing one. Add(key, value) only inserts, throwing if the key already exists.

Use Add when a duplicate key should be an error, and the indexer when overwriting is fine.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var d = new Dictionary<string, int>();
        d["x"] = 1;
        d["x"] = 2;     // overwrite, fine
        Console.WriteLine(d["x"]);
    }
}

Removing Entries

Remove(key) deletes a pair and returns true if the key was present, on average O(1).

An overload returns the removed value via an out parameter, handy when you want to delete and use the value in one step.

var d = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 };
bool removed = d.Remove("a");   // true
bool again = d.Remove("a");     // false

Iterating Pairs

Looping yields KeyValuePair<TKey, TValue> items. Deconstruct them into a key and value for clean code.

Enumeration order is not guaranteed; never rely on the order entries were inserted. Use Keys or Values to iterate just one side.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var d = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 };
        foreach (var (key, val) in d)
            Console.WriteLine($"{key}={val}");
    }
}

Counting with a Dictionary

A classic use is tallying occurrences. For each item, increment its count, starting from zero if it is new.

This pattern runs in O(n) for n items because each lookup and update is O(1), versus O(n squared) if you scanned a list each time.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var counts = new Dictionary<char, int>();
        foreach (char c in "banana")
            counts[c] = counts.GetValueOrDefault(c) + 1;
        Console.WriteLine(counts['a']);
    }
}

Key Equality Matters

Lookups rely on GetHashCode and Equals of the key type. Built-in types and string work out of the box.

For custom class keys, override both methods (or use a record), otherwise two equal-looking keys hash differently and lookups fail.

var byName = new Dictionary<string, int>(
    System.StringComparer.OrdinalIgnoreCase);
byName["Hi"] = 1;
bool found = byName.ContainsKey("HI"); // true

Choosing a Value Type

Values can be anything, including lists. A Dictionary<string, List<int>> groups many values under one key.

When inserting into such a structure, create the inner list on first use, then add to it. This builds a grouped, multi-value map.

var groups = new Dictionary<string, List<int>>();
void Add(string k, int v) {
    if (!groups.TryGetValue(k, out var list))
        groups[k] = list = new List<int>();
    list.Add(v);
}

Quick Check

Choose the safest way to read a possibly-missing key.

Recap

Dictionary<K,V> gives average O(1) lookup, insert, and remove by key, backed by a hash table.

Prefer TryGetValue over the throwing indexer, keep keys unique, and ensure custom key types implement proper equality and hashing. Iteration order is undefined.

Frequently asked questions

Is the “Dictionary Lookups” lesson free?

Yes — the full text of “Dictionary Lookups” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Dictionary Lookups”?

Fast key-value access. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Dictionary Lookups” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. List in Practice
  2. Dictionary Lookups
  3. HashSet and Uniqueness
  4. Choosing a Collection
← Back to C# Academy