c# · level 2 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A finds a value by its .
A Dictionary stores pairs: a key and the value that goes with it, like a coat check where each ticket fetches one coat. Dictionary<string, int> means the keys are strings and the values are ints. You look things up by key, never by position.
That type is long to type twice, so write instead and C# copies the type from the right. prices["tea"] = 2 adds a pair, or replaces the value if the key is already there. Each key appears only once.
Reading a key that is not there stops the program with KeyNotFoundException. Ask first with : prices.ContainsKey("soup") gives True or False.
using System;
using System.Collections.Generic;
var prices = new Dictionary<string, int>();
prices["tea"] = 2;
prices["cake"] = 3;
prices["tea"] = 3;
Console.WriteLine(prices["tea"]);
Console.WriteLine(prices.Count);
Console.WriteLine(prices.ContainsKey("soup")); Keys care about capital letters: "Tea" and "tea" are different keys.
guess first
Rex has a birthday. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
var ages = new Dictionary<string, int>();
ages["Rex"] = 3;
ages["Bella"] = 5;
ages["Rex"] = 4;
Console.WriteLine($"{ages["Rex"]} {ages.Count}");
your turn
Your turn. Teach it a capital city.
On line 6, add a country and its capital. On line 7, pick that country to look up. Press run.
output
press run to see what happens
fix it
The shop cannot find its apples. Can you fix it?
output
press run to see what happens
- C# stops with
KeyNotFoundExceptionon line 7. Compare the key it looks up with the key stored on line 5. - Keys care about capital letters.
Applesandapplesare different keys. - Change
stock["Apples"]tostock["apples"]on line 7, then press run.
nailed it
you can look anything up by name. :D
- A
Dictionarystores key and value pairs. dict[key] = valueadds a pair or replaces its value.- Check with
.ContainsKeybefore reading a key.
new words in your collection
- Dictionary
- key
- var
- ContainsKey
This lesson isn’t saved. A free account remembers every lesson you finish.