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:
95Be 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
EasyCreate a method named GetValueByKey that takes two arguments:
- A Dictionary<string, int> (dictionary).
- 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}");
}
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap