Menu
Coddy logo textTech

Nested HashMap

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 53 de 66.

Un HashMap anidado es un HashMap donde los valores mismos son HashMaps. Esto es útil para organizar datos jerárquicos.

Crea un HashMap anidado para almacenar las calificaciones de los estudiantes por materia:

// Crea el HashMap exterior (student -> subjects)
Dictionary<string, Dictionary<string, int>> studentGrades = new Dictionary<string, Dictionary<string, int>>();

// Crea un HashMap interior para un estudiante (subject -> grade)
Dictionary<string, int> alexGrades = new Dictionary<string, int>();

// Agrega calificaciones al HashMap interior
alexGrades.Add("Math", 90);
alexGrades.Add("Science", 85);

// Agrega el HashMap interior al HashMap exterior
studentGrades.Add("Alex", alexGrades);

Acceder a un valor anidado:

// Acceder a la calificación de Matemáticas de Alex
int mathGrade = studentGrades["Alex"]["Math"]; // Devuelve 90

Agregar otro estudiante con sus calificaciones:

// Crear otro HashMap interno
Dictionary<string, int> sarahGrades = new Dictionary<string, int>();
sarahGrades.Add("Math", 95);
sarahGrades.Add("Science", 92);

// Agregar al HashMap externo
studentGrades.Add("Sarah", sarahGrades);
challenge icon

Desafío

Intermedio

Crea un método llamado AddCourseGrade que toma cuatro argumentos:

  1. Un Diccionario anidado que representa las calificaciones de los estudiantes: Dictionary<string, Dictionary<string, int>> grades
  2. Un nombre de estudiante (string)
  3. Un nombre de curso (string)
  4. Una calificación (int)

El método debe:

  • Si el estudiante no existe en el diccionario, crear una nueva entrada para él
  • Agregar el curso y la calificación al registro del estudiante
  • Si el curso ya existe para ese estudiante, actualizar la calificación
  • Imprimir "Added [course] grade for [student]: [grade]" después de agregar/actualizar

Hoja de referencia

Un HashMap anidado es un HashMap donde los valores en sí son HashMaps, útil para organizar datos jerárquicos.

Crear un HashMap anidado:

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);

Acceder a valores anidados:

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

Agregar otra entrada:

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

Pruébalo tú mismo

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)
    {
        // Escribe tu código aquí
    }
    
    // Ignora el código principal, convierte string a un 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 iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo