C# Dictionaries
Dictionaries are one of the most useful collection types in C#, allowing you to store and retrieve values based on unique keys. Unlike arrays or lists where you access elements by their position, dictionaries let you access elements using meaningful keys that you define.
What is a Dictionary?
A dictionary in C# is a collection of key-value pairs. Each key in the dictionary must be unique, and you use this key to store and retrieve the associated value. Think of a dictionary like a real-world dictionary where words (keys) have definitions (values), or like a phone book where names (keys) are associated with phone numbers (values).
Dictionaries are implemented through the Dictionary<TKey, TValue>
class in the System.Collections.Generic
namespace, where:
TKey
represents the type of keys in the dictionaryTValue
represents the type of values in the dictionary
Creating a Dictionary
Let's see how to create and initialize dictionaries in C#:
// Import the necessary namespace
using System.Collections.Generic;
// Creating an empty dictionary (string keys, int values)
Dictionary<string, int> ages = new Dictionary<string, int>();
// Creating and initializing a dictionary with collection initializer
Dictionary<string, string> capitals = new Dictionary<string, string>()
{
{ "USA", "Washington D.C." },
{ "UK", "London" },
{ "France", "Paris" },
{ "Germany", "Berlin" }
};
// Alternative initialization syntax (C# 6.0+)
Dictionary<string, string> countries = new Dictionary<string, string>()
{
["USA"] = "United States of America",
["UK"] = "United Kingdom",
["FR"] = "France"
};
Adding Items to a Dictionary
You can add items to a dictionary after it's created:
Dictionary<string, int> studentScores = new Dictionary<string, int>();
// Adding items with the Add method
studentScores.Add("Alice", 95);
studentScores.Add("Bob", 87);
studentScores.Add("Charlie", 92);
// Adding items using indexer syntax
studentScores["David"] = 78;
studentScores["Eve"] = 89;
Console.WriteLine($"Number of students: {studentScores.Count}"); // Output: Number of students: 5
Accessing Dictionary Values
There are several ways to retrieve values from a dictionary:
Dictionary<string, int> studentScores = new Dictionary<string, int>()
{
{ "Alice", 95 },
{ "Bob", 87 },
{ "Charlie", 92 }
};
// Access using indexer (will throw KeyNotFoundException if key doesn't exist)
int aliceScore = studentScores["Alice"];
Console.WriteLine($"Alice's score: {aliceScore}"); // Output: Alice's score: 95
// Using TryGetValue (safer approach)
if (studentScores.TryGetValue("David", out int davidScore))
{
Console.WriteLine($"David's score: {davidScore}");
}
else
{
Console.WriteLine("David is not in the dictionary."); // This will be printed
}
// Checking if a key exists before accessing
if (studentScores.ContainsKey("Bob"))
{
Console.WriteLine($"Bob's score: {studentScores["Bob"]}"); // Output: Bob's score: 87
}
Updating Dictionary Values
You can modify existing values in a dictionary:
Dictionary<string, int> studentScores = new Dictionary<string, int>()
{
{ "Alice", 95 },
{ "Bob", 87 },
{ "Charlie", 92 }
};
// Update using indexer
studentScores["Bob"] = 90;
Console.WriteLine($"Bob's updated score: {studentScores["Bob"]}"); // Output: Bob's updated score: 90
// Update or add (if key doesn't exist)
studentScores["David"] = 78; // This adds a new entry
Removing Items from a Dictionary
There are multiple ways to remove items:
Dictionary<string, int> studentScores = new Dictionary<string, int>()
{
{ "Alice", 95 },
{ "Bob", 87 },
{ "Charlie", 92 },
{ "David", 78 }
};
// Remove by key
bool removed = studentScores.Remove("Charlie");
Console.WriteLine($"Charlie removed: {removed}"); // Output: Charlie removed: True
// Try to remove non-existent key
bool notRemoved = studentScores.Remove("Frank");
Console.WriteLine($"Frank removed: {notRemoved}"); // Output: Frank removed: False
// Clear all items
studentScores.Clear();
Console.WriteLine($"Items after Clear: {studentScores.Count}"); // Output: Items after Clear: 0
Iterating Through a Dictionary
You can loop through dictionaries in several ways:
Dictionary<string, string> capitals = new Dictionary<string, string>()
{
{ "USA", "Washington D.C." },
{ "UK", "London" },
{ "France", "Paris" },
{ "Germany", "Berlin" }
};
// Iterating through KeyValuePair items
Console.WriteLine("Countries and their capitals:");
foreach (KeyValuePair<string, string> pair in capitals)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
// Using deconstruction (C# 7.0+)
foreach (var (country, capital) in capitals)
{
Console.WriteLine($"The capital of {country} is {capital}");
}
// Iterating through only keys
Console.WriteLine("\nCountries:");
foreach (string country in capitals.Keys)
{
Console.WriteLine(country);
}
// Iterating through only values
Console.WriteLine("\nCapitals:");
foreach (string capital in capitals.Values)
{
Console.WriteLine(capital);
}
Output:
Countries and their capitals:
USA: Washington D.C.
UK: London
France: Paris
Germany: Berlin
Countries:
USA
UK
France
Germany
Capitals:
Washington D.C.
London
Paris
Berlin
Dictionary Properties and Methods
Here are some important properties and methods of the Dictionary<TKey, TValue>
class:
Property/Method | Description |
---|---|
Count | Gets the number of key-value pairs in the dictionary |
Keys | Gets a collection containing the keys |
Values | Gets a collection containing the values |
Add(key, value) | Adds a key-value pair |
Clear() | Removes all keys and values |
ContainsKey(key) | Determines whether the dictionary contains the specified key |
ContainsValue(value) | Determines whether the dictionary contains a specific value |
Remove(key) | Removes the value with the specified key |
TryGetValue(key, out value) | Gets the value associated with the key if it exists |
Real-World Applications
Example 1: Product Catalog
Dictionary<string, decimal> productPrices = new Dictionary<string, decimal>()
{
{ "Apple", 0.99m },
{ "Banana", 0.59m },
{ "Orange", 0.79m },
{ "Milk", 2.49m },
{ "Bread", 2.29m }
};
// Shopping cart with product and quantity
Dictionary<string, int> shoppingCart = new Dictionary<string, int>()
{
{ "Apple", 5 },
{ "Milk", 1 },
{ "Bread", 2 }
};
// Calculate total price
decimal totalPrice = 0;
foreach (var item in shoppingCart)
{
string product = item.Key;
int quantity = item.Value;
if (productPrices.ContainsKey(product))
{
decimal itemTotal = productPrices[product] * quantity;
totalPrice += itemTotal;
Console.WriteLine($"{quantity} x {product} = ${itemTotal:F2}");
}
}
Console.WriteLine($"Total: ${totalPrice:F2}");
Output:
5 x Apple = $4.95
1 x Milk = $2.49
2 x Bread = $4.58
Total: $12.02
Example 2: Word Frequency Counter
string text = "The quick brown fox jumps over the lazy dog. The dog was not happy about the fox.";
// Split the text into words and convert to lowercase
string[] words = text.ToLower().Split(new char[] { ' ', '.', ',', '!', '?' }, StringSplitOptions.RemoveEmptyEntries);
// Count frequency of each word
Dictionary<string, int> wordFrequency = new Dictionary<string, int>();
foreach (string word in words)
{
if (wordFrequency.ContainsKey(word))
{
wordFrequency[word]++;
}
else
{
wordFrequency[word] = 1;
}
}
// Display word frequencies
Console.WriteLine("Word Frequency:");
foreach (var pair in wordFrequency.OrderByDescending(p => p.Value))
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
Output:
Word Frequency:
the: 3
fox: 2
dog: 2
quick: 1
brown: 1
jumps: 1
over: 1
lazy: 1
was: 1
not: 1
happy: 1
about: 1
Dictionary Performance Considerations
Dictionaries in C# use a hash table implementation, providing:
- Fast lookups: O(1) average time complexity for retrieving, adding, and removing items
- Memory usage: Higher memory footprint than arrays or lists
- Unordered: Dictionary items are not stored in any particular order
For cases where you need an ordered dictionary, consider using SortedDictionary<TKey, TValue>
(which uses a self-balancing tree) or OrderedDictionary
(which maintains insertion order).
Summary
Dictionaries in C# are powerful collections for storing key-value pairs that provide:
- Fast lookups by unique keys
- Flexibility in key and value types
- Easy addition, removal, and updating of elements
- Multiple ways to iterate through items
When working with data that has natural key-value relationships (like IDs and objects, words and definitions, etc.), dictionaries are often the most appropriate collection to use.
Exercises
-
Create a dictionary that stores student names as keys and a list of their grades as values. Calculate each student's average grade.
-
Build a simple phone book application that lets users add, search, update, and delete contacts using a dictionary.
-
Create a program that reads a text file and counts the occurrences of each character, storing results in a dictionary.
-
Implement a cache using a dictionary where keys are resource identifiers and values are the actual resources.
-
Create a dictionary-based inventory system for a game where keys are item names and values are item quantities.
Additional Resources
- Official Microsoft Documentation on
Dictionary<TKey,TValue>
- C# Collection Types
- Dictionary vs Hashtable in C#
Happy coding with dictionaries!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)