Menu
Coddy logo textTech

Modifying Dictionaries

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

Los diccionarios en C# son mutables, lo que significa que puedes modificarlos después de crearlos. Aquí están las formas comunes de modificar un Dictionary:

Agregar un nuevo par clave-valor:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);

Actualizar el valor de una clave existente:

// Primero verificar si la clave existe
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // Actualiza "apple" para tener el valor 15
}

Eliminar un par clave-valor:

// Eliminar la entrada "apple"
inventory.Remove("apple");

Borrar todas las entradas:

// Eliminar todos los pares clave-valor
inventory.Clear();
challenge icon

Desafío

Fácil

Crea un método llamado UpdateInventory que tome tres argumentos:

  1. Un Dictionary<string, int> que representa un inventario
  2. Una cadena que representa el nombre de un artículo
  3. Un entero que representa la nueva cantidad

El método debe:

  • Si el artículo existe en el inventario, actualiza su cantidad
  • Si el artículo no existe, agrégalo con la cantidad dada
  • Imprime el inventario actualizado en el formato: "Item: [quantity]" (un artículo por línea)

Hoja de referencia

Los diccionarios en C# son mutables y pueden modificarse después de su creación.

Agregar un nuevo par clave-valor:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);

Actualizar el valor de una clave existente:

// Primero verificar si la clave existe
if (inventory.ContainsKey("apple"))
{
    inventory["apple"] = 15;  // Actualiza "apple" para tener valor 15
}

Eliminar un par clave-valor:

// Eliminar la entrada "apple"
inventory.Remove("apple");

Limpiar todas las entradas:

// Eliminar todos los pares clave-valor
inventory.Clear();

Pruébalo tú mismo

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

class Program
{
    public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
    {
        // Escribe tu código aquí
        
        // Imprime el inventario actualizado
        // No elimines esto
        foreach (KeyValuePair<string, int> entry in inventory)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
    // Ignora el código principal, convierte string a un HashMap
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Read first line to check if it's JSON format
        string firstLine = Console.ReadLine();
        
        // Check if input is in JSON format
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Process JSON input for initial inventory
                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);
                    }
                }
                
                // Read the item to update and its quantity
                string updateItemJson = Console.ReadLine();
                // Check if update item is in JSON format with quotes
                Match itemMatch = Regex.Match(updateItemJson, @"""([^""]+)""");
                string updateItem = itemMatch.Success ? itemMatch.Groups[1].Value : updateItemJson;
                
                int updateQuantity = int.Parse(Console.ReadLine());
                
                UpdateInventory(inventory, updateItem, updateQuantity);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            try
            {
                // Process traditional input format
                int initialCount = int.Parse(firstLine);
                for (int i = 0; i < initialCount; i++)
                {
                    string item = Console.ReadLine();
                    int quantity = int.Parse(Console.ReadLine());
                    inventory.Add(item, quantity);
                }
                
                // Read the item to update and its quantity
                string updateItem = Console.ReadLine();
                int updateQuantity = int.Parse(Console.ReadLine());
                
                UpdateInventory(inventory, updateItem, updateQuantity);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
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