Menu
Coddy logo textTech

Accessing Values

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

In C#, we use Dictionary<TKey, TValue> as the equivalent of HashMap. After adding items to a Dictionary, you'll need to retrieve them.

Create a Dictionary with string keys and int values:

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

Add some entries:

studentScores.Add("John", 95);
studentScores.Add("Mary", 88);

Accessing a value using a key:

int johnScore = studentScores["John"];

After executing the above code, johnScore contains:

95

Be careful! If you try to access a key that doesn't exist, you'll get a KeyNotFoundException:

// This will throw an exception if "Bob" isn't in the dictionary
int bobScore = studentScores["Bob"];
challenge icon

Challenge

Easy

Create a method named GetValueByKey that takes two arguments:

  1. A Dictionary<string, int> (dictionary).
  2. A string (key) to look up.

The method should try to access the value for the given key and:

  • If the key exists, print the value.
  • If the key doesn't exist, print "Key not found".

Cheat sheet

Create a Dictionary with string keys and int values:

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

Add entries to the Dictionary:

studentScores.Add("John", 95);
studentScores.Add("Mary", 88);

Access a value using a key:

int johnScore = studentScores["John"];

Accessing a non-existent key will throw a KeyNotFoundException:

// This will throw an exception if "Bob" isn't in the dictionary
int bobScore = studentScores["Bob"];

Try it yourself

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
    {
        // Write code here
    }
    
    static void Main(string[] args)
    {
        // Read in a dictionary in JSON format: {"key1":value1,"key2":value2}
        string dictionaryInput = Console.ReadLine();
        string key = Console.ReadLine();
        
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        
        // Parse the input string to create a dictionary
        if (!string.IsNullOrEmpty(dictionaryInput))
        {
            try
            {
                // Check if input is in JSON format
                if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
                {
                    // Remove the curly braces
                    string jsonContent = dictionaryInput.Substring(1, dictionaryInput.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);
                            dictionary.Add(keyMatch, valueMatch);
                        }
                    }
                }
                // Handle the original format "key1:value1,key2:value2" as fallback
                else
                {
                    string[] pairs = dictionaryInput.Split(',');
                    foreach (string pair in pairs)
                    {
                        string[] keyValue = pair.Split(':');
                        if (keyValue.Length == 2)
                        {
                            dictionary.Add(keyValue[0], int.Parse(keyValue[1]));
                        }
                    }
                }
                
                GetValueByKey(dictionary, key);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow