Skip to content

Exercise 9 of 10 · Dictionaries

Town Hall Attendance by District

What you will make

A program that tracks how many residents from each district signed in to a town hall meeting and prints a per-district report.

The one new idea: Using a Dictionary<string,int> and ContainsKey to look up values safely by key

A dictionary maps a name to a value directly, which is a much more natural fit than an array or list when what you really have are labeled counts, not a plain sequence.

Go straight to the code ↓

Sometimes what you really have is a set of labeled values, not just a sequence — a count for each district, a score for each student. A Dictionary<TKey, TValue> stores exactly that kind of mapping: dictionary[key] = value adds or updates an entry, and dictionary[key] reads it back. But reading a key that was never added throws a KeyNotFoundException at runtime, so it's important to check dictionary.ContainsKey(key) first whenever a key's presence isn't guaranteed.

Worked example

Here's a dictionary mapping a workbook's chapter names to their page counts:

C#
Dictionary<string, int> pagesByChapter = new Dictionary<string, int>();
pagesByChapter["Fractions"] = 12;
pagesByChapter["Geometry"] = 9;

string lookup = "Statistics";
int pages;
if (pagesByChapter.ContainsKey(lookup))
{
    pages = pagesByChapter[lookup];
}
else
{
    pages = 0;
}

Console.WriteLine($"{lookup}: {pages} pages");
Output
Statistics: 0 pages

Because "Statistics" was never added to pagesByChapter, ContainsKey returns false, so the code safely falls back to 0 instead of crashing.

Your turn

The starter code tracks town hall sign-ins per district and walks through a fixed list of district names, including "West", to print each one's count. But "West" was never added to the dictionary, so the direct lookup attendanceByDistrict[district] crashes as soon as the loop reaches it. Fix the lookup so it checks whether the key exists first, and treats a missing district as 0 sign-ins instead of crashing.

If something goes wrong

A KeyNotFoundException almost always means you indexed a dictionary with a key that was never inserted — check every key you're looking up against every key you actually added with dictionary[key] = value. If the total looks off by exactly the count you expected from a missing district, that's a sign the fallback branch isn't running, or isn't adding 0 the way you intended.

Write your code

Runs in your browser. Press Run (or Ctrl/Cmd+Enter) and the output is checked for you.

Ctrl/Cmd+Enter to run

Press Esc then Tab to move keyboard focus out of the code editor.

Ready
Output will appear here after you run your code.

The runtime is starting in the background. You can type now — it will be ready before you are.

The answer appears here once you have run your code at least once.

Things that often go wrong here

Looking up a dictionary key with [key] without checking ContainsKey first.
If the key was never added, this throws a KeyNotFoundException at runtime instead of failing gracefully.
Assuming every key you might want to check was definitely inserted.
In practice, some expected keys — like a district with zero sign-ins — may never get added in the first place.
Mixing up dictionary [ ] syntax with array indexing.
A dictionary's [ ] takes a key of the declared key type, not a positional index, unless that key type happens to be int.

Want a blank editor instead? Open the C# playground.