A dictionary
is a data structure that stores a collection of name-value pairs in the ASP framework. Each name-value pair maps the name (key) to the corresponding value (item) it is linked to.
The following is the syntax used to create a dictionary in ASP. Unlike the declaration of dictionaries found in other programming languages, in ASP, after declaring the variable for the dictionary, you must then set
it to a newly created Scripting.Dictionary
server object.
The main advantage of using a dictionary over an array is that a dictionary contains built-in properties and methods which allow you to access important information and perform certain functions much quicker than in a typical array.
These are the functions built into the dictionary data structure. The following are a few of the most common ones and their descriptions:
Method | Description |
---|---|
Add |
Allows you to add a new key-item pair in your dictionary |
Exists |
Checks whether a certain key exists in the dictionary. Returns either true or false accordingly |
Items |
Gives you an array of all the items stored in the dictionary |
Keys |
Gives you an array of all the keys stored in the dictionary |
Remove |
Allows you to remove a certain key-item pair entry in the dictionary |
These are functions that provide data regarding the entries stored in the dictionary or allows you to edit them.
Properties | Description |
---|---|
Count |
Tells you the number of entries in the dictionary |
CompareMode |
Allows you to compare keys in a dictionary |
Item |
Can be used to get the item corresponding to a certain key or set this value |
Key |
Used to change the key of an existing entry |
In the following example, we first declare and populate a dictionary. After this, we first check the presence of a key in the dictionary and print out its corresponding item value if present. Next, we remove that key-item pair and once again check for its existence in the dictionary and print out an error message when it is not found.
<%Dim dictSet dict=Server.CreateObject("Scripting.Dictionary")dict.Add "a","apple"dict.Add "b","ball"dict.Add "c","cat"If dict.Exists("a") ThenResponse.Write("The value corresponding to the 'a' key is: ", & dict.Item("a"))ElseResponse.Write("Sorry, this entry doesn't exist ")End Ifdict.Remove("a")If dict.Exists("a") ThenResponse.Write("The value corresponding to the 'a' key is: ", & dict.Item("a"))ElseResponse.Write("Sorry, this entry doesn't exist ")End If%>
output:The value corresponding to the 'a' key is: appleSorry, this entry doesn't exist