Dictionary<K,V>
In this page:
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>
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}");
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: