What Are Dictionaries?
メニューを表示するにはスワイプしてください
In Arrays, we access data through indexing (arrayName[index]). In an Array, every value (element) has a unique index, which is used for accessing that value, therefore we can say that an Array has an index-value structure.
There's a similar structure called a Dictionary, in which we have key-value pairs instead. While an index is always an integer number, a key can be of any basic data type, however it's commonly a string.
The following illustration shows an example illustration of dictionary which stores the number of different fruits:
Creating a Dictionary
We can declare a dictionary using the following syntax:
IDictionary<keyDataType, valueDataType> dictionaryName = new Dictionary<keyDataType, valueDataType>();
Here keyDataType represents the data type of the key while the valueDataType represents the data type of the values. dictionaryName is the name of the dictionary.
An implicit declaration is also valid:
var dictionaryName = new Dictionary<keyDataType, valueDataType>();
Adding Data
We can use the Add method to add items to the dictionary:
dictionaryName.Add(keyName, value);
Accessing Data
We can access the data in dictionaries using the keys:
dictionaryName[keyName]
Following is an example which demonstrates all three:
index.cs
12345678910111213141516171819202122using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { var student = new Dictionary<string, string>(); student.Add("name", "Noah"); student.Add("country", "Netherlands"); student.Add("subject", "Computer Science"); Console.WriteLine(student["name"]); Console.WriteLine(student["country"]); Console.WriteLine(student["subject"]); } } }
Each key in a dictionary must be unique. In case we try to add a key which already exists, the compiler will show an error.
In Dictionaries, Count attribute shows the number of key-value pairs stored in it. Remove method takes in a key and removes that key-value pair from the dictionary. Clear method simply removes all key-value pairs from a dictionary. It will be a good code reading exercise to read and understand the usage of Count, Remove and Clear from the following code:
index.cs
1234567891011121314151617181920212223242526using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { var numbers = new Dictionary<int, string>(); numbers.Add(0, "Zero"); numbers.Add(1, "One"); numbers.Add(2, "Two"); numbers.Add(3, "Three"); numbers.Add(4, "Four"); numbers.Add(5, "Five"); Console.WriteLine(numbers.Count); // Output: 6 numbers.Remove(3); Console.WriteLine(numbers.Count); // Output: 5 numbers.Clear(); Console.WriteLine(numbers.Count); // Output: 0 } } }
1. What module must be imported for using dictionaries?
2. What is the correct syntax for creating a dictionary?
3. What will be the output of the following code?
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください