Menu
Coddy logo textTech

Nested HashMap

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

A nested HashMap is a HashMap where the values themselves are HashMaps. This is useful for organizing hierarchical data.

Create a nested HashMap to store student grades by subject:

// Create the outer HashMap (student -> subjects)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Create an inner HashMap for a student (subject -> grade)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Add grades to the inner HashMap
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Add the inner HashMap to the outer HashMap
studentGrades.Add("Alex", alexGrades);

Access a nested value:

// Access Alex's Math grade
int mathGrade = studentGrades["Alex"]["Math"]; // Returns 90

Add another student with their grades:

// Create another inner HashMap
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Add to the outer HashMap
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Challenge

Medium

Create a method named AddCourseGrade that takes four arguments:

  1. A nested Dictionary representing student grades: Dictionary<string, Dictionary<string, int>> grades
  2. A student name (string)
  3. A course name (string)
  4. A grade (int)

The method should:

  • If the student doesn't exist in the dictionary, create a new entry for them
  • Add the course and grade to the student's record
  • If the course already exists for that student, update the grade
  • Print "Added [course] grade for [student]: [grade]" after adding/updating

Cheat sheet

A nested HashMap is a HashMap where the values themselves are HashMaps, useful for organizing hierarchical data.

Create a nested HashMap:

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

// Create inner HashMap
Dictionary<string, int> alexGrades = new Dictionary<string, int>();
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Add to outer HashMap
studentGrades.Add("Alex", alexGrades);

Access nested values:

int mathGrade = studentGrades["Alex"]["Math"]; // Returns 90

Add another entry:

Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);
studentGrades.Add("Sarah", sarahGrades);

Try it yourself

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

class Program
{
    public static void AddCourseGrade(Dictionary<string, Dictionary<string, int>> grades, string student, string course, int grade)
    {
        // Write your code here
    }
    
    // Ignore the main code, it converts string to a HashMap
    static void Main(string[] args)
    {
        // Check if first line might be JSON
        string firstLine = Console.ReadLine();
        
        Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();
        string student;
        string course;
        int grade;
        
        // JSON format input
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Parse existing student grades from JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                string studentPattern = @"""([^""]+)""\s*:\s*\{([^\}]+)\}";
                
                MatchCollection studentMatches = Regex.Matches(jsonContent, studentPattern);
                foreach (Match studentMatch in studentMatches)
                {
                    string studentName = studentMatch.Groups[1].Value;
                    string coursesJson = studentMatch.Groups[2].Value;
                    
                    Dictionary<string, int> courseGrades = new Dictionary<string, int>();
                    string coursePattern = @"""([^""]+)""\s*:\s*(\d+)";
                    
                    MatchCollection courseMatches = Regex.Matches(coursesJson, coursePattern);
                    foreach (Match courseMatch in courseMatches)
                    {
                        string courseName = courseMatch.Groups[1].Value;
                        int courseGrade = int.Parse(courseMatch.Groups[2].Value);
                        courseGrades.Add(courseName, courseGrade);
                    }
                    
                    studentGrades.Add(studentName, courseGrades);
                }
                
                // Parse student, course, and grade for the operation
                string studentInput = Console.ReadLine();
                Match studentNameMatch = Regex.Match(studentInput, @"""([^""]+)""");
                student = studentNameMatch.Success ? studentNameMatch.Groups[1].Value : studentInput;
                
                string courseInput = Console.ReadLine();
                Match courseNameMatch = Regex.Match(courseInput, @"""([^""]+)""");
                course = courseNameMatch.Success ? courseNameMatch.Groups[1].Value : courseInput;
                
                grade = int.Parse(Console.ReadLine());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            try
            {
                // Traditional input
                student = firstLine;
                course = Console.ReadLine();
                grade = int.Parse(Console.ReadLine());
                
                // Create an example entry
                Dictionary<string, int> johnGrades = new Dictionary<string, int>();
                johnGrades.Add("Math", 88);
                studentGrades.Add("John", johnGrades);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing traditional input: {ex.Message}");
                return;
            }
        }
        
        AddCourseGrade(studentGrades, student, course, grade);
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow