Modifying Dictionaries
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 50번째.
C#의 Dictionary는 가변(mutable)입니다. 즉, 생성한 후에 수정할 수 있습니다. Dictionary를 수정하는 일반적인 방법은 다음과 같습니다:
새로운 키-값 쌍을 추가:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);기존 키의 값을 업데이트:
// 먼저 키가 존재하는지 확인
if (inventory.ContainsKey("apple"))
{
inventory["apple"] = 15; // "apple"을 값 15로 업데이트
}키-값 쌍 제거:
// "apple" 항목 제거
inventory.Remove("apple");모든 항목 지우기:
// Remove all key-value pairs
inventory.Clear();챌린지
쉬움UpdateInventory라는 이름의 메서드를 생성하세요. 이 메서드는 세 개의 인수를 받습니다:
- 재고를 나타내는 Dictionary<string, int>
- 아이템 이름을 나타내는 string
- 새로운 수량을 나타내는 int
이 메서드는 다음을 수행해야 합니다:
- 아이템이 재고에 존재하면, 그 수량을 업데이트합니다
- 아이템이 존재하지 않으면, 주어진 수량으로 추가합니다
- 업데이트된 재고를 형식: "Item: [quantity]"로 출력합니다 (한 줄에 하나의 아이템)
치트 시트
C#의 딕셔너리는 가변적이며 생성 후에 수정할 수 있습니다.
새로운 키-값 쌍 추가:
Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apple", 10);기존 키의 값 업데이트:
// 먼저 키가 존재하는지 확인
if (inventory.ContainsKey("apple"))
{
inventory["apple"] = 15; // "apple"을 값 15로 업데이트
}키-값 쌍 제거:
// "apple" 항목 제거
inventory.Remove("apple");모든 항목 지우기:
// 모든 키-값 쌍 제거
inventory.Clear();직접 해보기
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void UpdateInventory(Dictionary<string, int> inventory, string item, int quantity)
{
// 여기에 코드를 작성하세요
// 업데이트된 재고를 출력하세요
// 이것을 제거하지 마세요
foreach (KeyValuePair<string, int> entry in inventory)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
}
// 메인 코드는 무시하세요, 문자열을 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}");
}
}
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
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