Dictionary<K,V>
A Dictionary looks up values by a key, like finding a word in a dictionary or a name in a phone book. Each key points quickly to its value.
In this page:
Syntax
Dictionary<KeyType, ValueType> dictName = new Dictionary<KeyType, ValueType>();
dictName[key] = value;
ValueType value = dictName[key];
dictName.ContainsKey(key);
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Reading a missing key with
dict[key], which throwsKeyNotFoundException; useTryGetValue. - Adding a key that already exists with
Add, which throwsArgumentException. - Using a mutable object as a key and changing it after adding, so it can no longer be found.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: