C#

[C#] 딕셔너리(Dictionary)

기리도 2022. 7. 8. 18:42
728x90

📕딕셔너리(Dictionary)


📖딕셔너리란?

딕셔너리는 데이터를 '키와 값'이라는 묶음으로 저장하는 데이터 집합이다. 딕셔너리 클래스는 System.Collections에 정의돼 있으며, 제네릭 형식이므로 모든 유형의 데이터를 저장할 수 있다. 데이터를 '키와 값'의 묶음으로 저장하기 때문에 저장 순서와 관계 없이 '키'를 통해 원하는 데이터를 곧바로 찾을 수 있다.

📌딕셔너리의 특징은 다음과 같다.

  • IDctionary<TKey, TValue> 인터페이스를 구현한다.
  • 같은 이름의 키는 반드시 하나여야 하며 'null'이어서는 안 된다.
  • 값은 'null'이어도 되며 복제되어도 된다.
  • 값은 해당 값과 연결된 키를 통해 접근할 수 있다.
  • 각 묶음은 KeyValuePair<TKey, TValue> 오브젝트로 저장된다.

📌딕셔너리 생성 방법

사용자는 딕셔너리 객체를 만들 때 저장될 키와 값의 형식을 정의해야 한다. 아래 코드를 보자.

IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");

//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three"); 

foreach(KeyValuePair<int, string> kvp in numberNames)
    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
		
//creating a dictionary using collection-initializer syntax
var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
};
		
foreach(var kvp in cities)
    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);

📌딕셔너리에 접근하기

값에 대응하는 키를 대괄호 안에 작성하면 값에 접근할 수 있으며,  ElementAt() 메서드를 사용하면 값과 키 모두에 접근할 수 있다.

var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
};

Console.WriteLine(cities["UK"]); //prints value of UK key
Console.WriteLine(cities["USA"]);//prints value of USA key
//Console.WriteLine(cities["France"]); // run-time exception: Key does not exist

//use ContainsKey() to check for an unknown key
if(cities.ContainsKey("France")){  
    Console.WriteLine(cities["France"]);
}

//use TryGetValue() to get a value of unknown key
string result;

if(cities.TryGetValue("France", out result))
{
    Console.WriteLine(result);
}

//use ElementAt() to retrieve key-value pair using index
for (int i = 0; i < cities.Count; i++)
{
    Console.WriteLine("Key: {0}, Value: {1}", 
                                            cities.ElementAt(i).Key, 
                                            cities.ElementAt(i).Value);
}

📌값 수정하기

딕셔너리의 값을 수정할 때도 해당 값에 대응하는 키를 사용해야 한다. 이때 키가 딕셔너리에 존재하지 않는다면 오류가 발생하므로 ContainsKey() 메서드를 사용해 키가 존재하는지 먼저 확인하는 게 좋다.

💡ContainsKey(): 키가 존재한다면 true를, 존재하지 않는다면 false를 반환한다.

var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
};

cities["UK"] = "Liverpool, Bristol"; // update value of UK key
cities["USA"] = "Los Angeles, Boston"; // update value of USA key
//cities["France"] = "Paris"; //throws run-time exception: KeyNotFoundException

if(cities.ContainsKey("France")){
    cities["France"] = "Paris";
}

📌키와 값 삭제하기

딕셔너리의 특정 키와 값을 삭제할 때는 Remove() 메서드를 사용한다. 수정할 때와 마찬가지로 해당 키와 값이 존재하지 않는다면 오류가 발생하므로 ContainsKey() 메서드로 존재 유무를 먼저 확인하는 게 좋다.

딕셔너리의 모든 키와 값을 삭제하고 싶다면 Clear() 메서드를 사용한다.

var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
};

cities.Remove("UK"); // removes UK 
//cities.Remove("France"); //throws run-time exception: KeyNotFoundException

if(cities.ContainsKey("France")){ // check key before removing it
    cities.Remove("France");
}

cities.Clear(); //removes all elements

📌딕셔너리의 계층구조

 

728x90

 

🔖인용 및 참고

https://www.tutorialsteacher.com/csharp/csharp-dictionary

 

C# Dictionary

C# - Dictionary The Dictionary is a generic collection that stores key-value pairs in no particular order. Dictionary Characteristics Dictionary stores key-value pairs. Comes under System.Collections.Generic namespace. Implements IDictionary interface. Key

www.tutorialsteacher.com

 

728x90