Labs ICT
โญ Pro Login

Dictionaries

Dictionaries store data in key-value pairs. Instead of looking up an item by its index like in a list, you look it up by a meaningful key. Think of it like a real dictionary โ€” you look up a word (the key) and find its definition (the value).

Creating a Dictionary

Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Amina", 22 },
    { "Bilal", 25 },
    { "Chukwuemeka", 24 }
};

The first type (string) is the key type, and the second type (int) is the value type. Keys must be unique โ€” you cannot have two entries with the same key.

Adding and Accessing Items

Dictionary<string, string> capitals = new Dictionary<string, string>();

// Adding items
capitals.Add("Nigeria", "Abuja");
capitals.Add("Ghana", "Accra");
capitals.Add("Kenya", "Nairobi");

// Accessing by key
Console.WriteLine(capitals["Nigeria"]);  // Abuja

// Modifying a value
capitals["Ghana"] = "Accra (updated)";

// Check if a key exists before accessing
if (capitals.ContainsKey("Kenya"))
{
    Console.WriteLine(capitals["Kenya"]);
}

Never access a key that does not exist โ€” it will throw a KeyNotFoundException. Always check with ContainsKey() first, or use TryGetValue().

Removing Items

capitals.Remove("Kenya");  // Remove by key

// Remove only if the key exists
bool removed = capitals.Remove("Ghana");  // true

Looping Through a Dictionary

Dictionary<string, int> students = new Dictionary<string, int>
{
    { "Amina", 85 },
    { "Bilal", 92 },
    { "Fatima", 78 }
};

// Loop through key-value pairs
foreach (KeyValuePair<string, int> pair in students)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}

// Or use deconstruction for cleaner syntax
foreach (var (name, score) in students)
{
    Console.WriteLine($"{name} scored {score}");
}

// Loop through just keys
foreach (string name in students.Keys)
{
    Console.WriteLine(name);
}

// Loop through just values
foreach (int score in students.Values)
{
    Console.WriteLine(score);
}

When to Use Dictionaries

Dictionaries are perfect when you need fast lookups by a key. For example:

  • Storing user profiles (key = user ID, value = profile data)
  • Translation maps (key = English word, value = Hausa translation)
  • Configuration settings (key = setting name, value = setting value)

If you just need an ordered collection of items, a List is usually simpler. Use dictionaries when the key-based lookup is important.

๐Ÿงช Quick Quiz

What are dictionaries used for?