A list finds things by position. A Dictionary finds things by a key you choose. Dictionary<string, int> maps strings to integers, for example a topic name to its minutes. Each key appears at most once, and looking one up stays fast however large the dictionary gets.
Adding and reading
Assigning to d[key] adds the entry or replaces the existing one. Reading d[key] for a key that isn't there throws an exception, so when a key might be missing, use ContainsKey to ask first, or TryGetValue to ask and read in one step. TryGetValue follows the same pattern you saw with out on Day 3.
var minutes = new Dictionary<string, int>();
minutes["Loops"] = 30;
minutes["Lists"] = 20;
minutes["Loops"] = 45;
Console.WriteLine(minutes.Count);
Console.WriteLine(minutes["Loops"]);
Console.WriteLine(minutes.ContainsKey("Records"));
if (minutes.TryGetValue("Records", out int found))
{
Console.WriteLine($"Found {found}");
}
else
{
Console.WriteLine("No entry for Records");
}Check your prediction
2
45
False
No entry for RecordsReading a missing key with [] looks like a normal line of code, and only fails when it runs.
var minutes = new Dictionary<string, int> { ["Loops"] = 30 };
Console.WriteLine(minutes["Lists"]);Check your prediction
Unhandled exception. System.Collections.Generic.KeyNotFoundExceptionTotalling by category
This is what a dictionary is best at. Go through some records, and for each one, update the running total for its key. The tricky part is the first time a key appears. TryGetValue leaves found as 0 when the key is missing, so a single line handles both cases.
var topics = new List<string> { "Loops", "Lists", "Loops" };
var minutes = new List<int> { 30, 20, 15 };
var totals = new Dictionary<string, int>();
for (int i = 0; i < topics.Count; i++)
{
totals.TryGetValue(topics[i], out int current);
totals[topics[i]] = current + minutes[i];
}
Console.WriteLine(totals["Loops"]);
Console.WriteLine(totals["Lists"]);Check your prediction
45
20Going through a dictionary
foreach over a dictionary gives you one entry at a time, each with a Key and a Value. You can also unpack them straight into two names. A dictionary doesn't promise any particular order. If order matters, sort it. A SortedDictionary has the same methods and keeps its keys in order, so reports come out the same on every run.
var minutes = new SortedDictionary<string, int>
{
["Records"] = 15,
["Loops"] = 45,
["Lists"] = 20,
};
foreach (var entry in minutes)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
foreach (var (topic, value) in minutes)
{
if (value > 30)
{
Console.WriteLine($"Long: {topic}");
}
}Check your prediction
Lists: 20
Loops: 45
Records: 15
Long: LoopsYour turn
Count words
Write CountWords(string text), which returns a SortedDictionary<string, int> with how many times each word appears. Words are separated by single spaces, and capitals should not matter. For "read review Read practice read", print practice: 1, read: 3 and review: 1. Make sure an empty string gives no words.
string text = "read review Read practice read";
Console.WriteLine(text);Hint 1: the idea
Normalize each word to lowercase before using it as a key, so Read and read land on the same entry.
Hint 2: a first step
Split the text and print each word in a loop. Check what splitting an empty string gives you before you start counting. If it gives you one empty piece, Split takes a second argument, StringSplitOptions.RemoveEmptyEntries, that drops empty pieces.
Show one solution
foreach (var (word, count) in CountWords("read review Read practice read"))
{
Console.WriteLine($"{word}: {count}");
}
Console.WriteLine(CountWords("").Count);
static SortedDictionary<string, int> CountWords(string text)
{
var counts = new SortedDictionary<string, int>();
foreach (string piece in text.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
string word = piece.ToLower();
counts.TryGetValue(word, out int current);
counts[word] = current + 1;
}
return counts;
}practice: 1
read: 3
review: 1
0Lowercasing each word before counting makes read and Read one word. RemoveEmptyEntries matters for the empty text: without it, "".Split(' ') gives one empty piece, which would be counted as a word. TryGetValue gives 0 for a new word, so there's no separate "first time" case.
"".Split(' ') gives an array containing one empty string, not an empty array. That's why the solution passes StringSplitOptions.RemoveEmptyEntries. Remove it, and predict what the last line prints.
Completion is saved in this browser only. It does not measure mastery.