← Back to C# Course | Chapter 9: Collections | Lesson 3 of 7

Dictionary<K,V>

In this page:

  1. Dictionary<K,V>

Dictionary<K,V>

Dictionary<TKey, TValue> stores key-value pairs and gives near-constant-time lookup by key. Keys must be unique; adding a duplicate key throws an exception unless you use the indexer to overwrite it. It's the go-to collection whenever you need to look values up by a meaningful identifier rather than a position.

Warning: Accessing a missing key with dict[key] throws a KeyNotFoundException — use TryGetValue to check safely.

Example: Dictionary<K,V>

markup
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Alice", 30 },
            { "Bob", 25 },
        };

        ages["Cara"] = 40;

        if (ages.TryGetValue("Bob", out int bobAge))
        {
            Console.WriteLine(bobAge);
        }

        foreach (KeyValuePair<string, int> pair in ages)
        {
            Console.WriteLine($"{pair.Key}: {pair.Value}");
        }
    }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.