0Pricing
C# Academy · Lesson

Dictionary Lookups

Fast key-value access.

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"]);
    }
}

All lessons in this course

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