Menu
Coddy logo textTech

Check If Key Exists

Part of the Logic & Flow section of Coddy's C# journey — lesson 48 of 66.

To check if a key exists in a HashMap (Dictionary in C#), you can use the ContainsKey() method.

First, create a Dictionary:

Dictionary<string, int> ages = new Dictionary<string, int>();

Add some key-value pairs:

ages.Add("John", 25);
ages.Add("Mary", 30);

Now check if a key exists:

bool exists = ages.ContainsKey("John");

After executing the above code, the variable exists will be true.

You can use this in a conditional statement:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}
challenge icon

Challenge

Easy

Create a method named CheckKeyExists that takes two arguments:

  • A Dictionary<string, int> (dictionary)
  • A string (key) to check

The method should check if the key exists in the dictionary and print:

  • "Key exists" if the key is found
  • "Key does not exist" if the key is not found

Cheat sheet

To check if a key exists in a Dictionary, use the ContainsKey() method:

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);

bool exists = ages.ContainsKey("John"); // returns true

Use in conditional statements:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}

Try it yourself

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // Write code here
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Reading inventory input - accepts both JSON format and line-by-line format
        string firstLine = Console.ReadLine();
        
        // Check if input is in JSON format
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Process JSON input
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Split by commas that are not inside quotes
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extract key and value using regex
                    Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                    if (match.Success)
                    {
                        string keyMatch = match.Groups[1].Value;
                        int valueMatch = int.Parse(match.Groups[2].Value);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Reading the key to check directly
                string keyToCheck = Console.ReadLine();
                CheckKeyExists(inventory, keyToCheck);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            // Process original line-by-line format
            string line = firstLine;
            
            // Read lines until an empty line is entered
            while (!string.IsNullOrEmpty(line))
            {
                try
                {
                    string[] parts = line.Split(':');
                    if (parts.Length == 2)
                    {
                        inventory.Add(parts[0], int.Parse(parts[1]));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error parsing line: {ex.Message}");
                }
                
                // Read next line
                line = Console.ReadLine();
            }
            
            // Reading the key to check
            string keyToCheck = Console.ReadLine();
            CheckKeyExists(inventory, keyToCheck);
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow