What is an ASP Dictionary?

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.

Syntax

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.

Advantage of using dictionaries

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.

Methods

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

Properties

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

Example

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 dict
Set dict=Server.CreateObject("Scripting.Dictionary")
dict.Add "a","apple"
dict.Add "b","ball"
dict.Add "c","cat"
If dict.Exists("a") Then
Response.Write("The value corresponding to the 'a' key is: ", & dict.Item("a"))
Else
Response.Write("Sorry, this entry doesn't exist ")
End If
dict.Remove("a")
If dict.Exists("a") Then
Response.Write("The value corresponding to the 'a' key is: ", & dict.Item("a"))
Else
Response.Write("Sorry, this entry doesn't exist ")
End If
%>
output:
The value corresponding to the 'a' key is: apple
Sorry, this entry doesn't exist
Copyright ©2024 Educative, Inc. All rights reserved