Start learning free

LESSON 128 OF 674 · DICTIONARIES

Checking for a Key in C#

Lesson

TL ; DR:

Call d.ContainsKey(key) to ask whether a Dictionary has a key. It returns true or false, so it goes in an if.


Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals["France"] = "Paris";
capitals["Japan"] = "Tokyo";

if (capitals.ContainsKey("Japan")) {
    Console.WriteLine(capitals["Japan"]);   // Tokyo
}

if (!capitals.ContainsKey("Spain")) {
    Console.WriteLine("No Spain");          // No Spain
}


Full lesson:

Reading a missing key is an error. capitals["Spain"] throws a KeyNotFoundException.

So check first. capitals.ContainsKey("Spain") is true when "Spain" is a key. It is false when it isn't.

Put ! in front for the opposite. !capitals.ContainsKey("Spain") is true here.

A value is not a key

ContainsKey looks only at the keys. capitals.ContainsKey("Paris") is false, because "Paris" is a value.

To look in the values, call ContainsValue("Paris").

A key must match exactly, upper and lower case too. capitals.ContainsKey("japan") is false.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, print Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with ! and ContainsKey. If so, print cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check