English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Dictionary (dictionary)

Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in an unspecified order.

Dictionary characteristics

  • Dictionary<TKey, TValue> stores key-value pairs.

  • It belongs to the System.Collection.Generic namespace.

  • Implement the IDictionary<TKey, TValue> interface.

  • Keys must be unique and cannot be null.

  • Values can be null or duplicate.

  • You can access the value by passing the relevant key in the indexer, for example myDictionary[key]

  • Elements are stored as KeyValuePair<TKey, TValue> objects.

Create a dictionary

You can create a dictionary that can store the types of keys and values by passing a Dictionary<TKey, TValue> object. The following example demonstrates how to create a dictionary and add key-value pairs.

IDictionary<int, 	string> 	numberNames 	= 	new 	Dictionary<int, 	string>();
numberNames.Add(1,	"One"); //Add keys using the Add() method/Value
numberNames.Add(2,	"Two");
numberNames.Add(3,	"Three");
//The following throws a runtime 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);
//Using collection-Dictionary 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);

In the above example, numberNames is a Dictionary<int, string> type dictionary, so it can store int keys and string values. Similarly, cities is a Dictionary<string, string> type dictionary, so it can store string keys and string values. Dictionaries cannot contain duplicate keys or null keys, while values can be duplicate keys or null keys. Keys must be unique; otherwise, a runtime exception will be thrown.

Accessing dictionary elements

You can access the dictionary using an indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from a specified index.

var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
}
Console.WriteLine(cities["UK"]); //Print the value of the UK key
Console.WriteLine(cities["USA"]);//Print the value of the USA key
//Console.WriteLine(cities["France"]); // runtime exception: run-runtime 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 the value of an unknown key
string result;
if (cities.TryGetValue("France", out result))
{
    Console.WriteLine(result);
}
//Retrieve key-value pairs by using ElementAt() through index
for (int i = 0; i < cities.Count;++)
{
    Console.WriteLine("Key: {0}, Value: {1}, cities.ElementAt(i).Key, cities.ElementAt(i).Value);
}

Update dictionary

Update the value of the key by specifying the key in the indexer. If the key does not exist in the dictionary, it will throw a KeyNotFoundException, so use the ContainsKey() method before accessing an unknown key

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 the value of the UK key
cities["USA"] = "Los Angeles, Boston"; //Update the value of the USA key
//cities["France"] = "Paris"; //Throw a runtime exception: KeyNotFoundException
if(cities.ContainsKey("France")){
    cities["France"] = "Paris";
}

Delete element from dictionary

The Remove() method deletes the existing key-value pair from the dictionary. The Clear() method deletes all elements from the dictionary.

var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
}
cities.Remove("UK"); // Remove UK 
//Remove UK before getting the key //Throw a runtime exception: KeyNotFoundException
if(cities.ContainsKey("France")){ // Check before getting the key
    Remove UK before getting the key
}
cities.Clear(); //Remove All Elements

Dictionary Class Hierarchy

The following figure illustrates the hierarchy of the generic Dictionary class.

You can learn about dictionary methods and properties on docs.microsoft.com.