ASP Dictionary Object
The Dictionary object is used to store information in name/value pairs.
Try it - Example
Does the Specified Key Exist?
This example demonstrates how to create a Dictionary object and then use the Exists method to check whether a specified key exists.
Returning an Array of All Items
This example demonstrates how to use the Items method to return an array of all items.
Returning an Array of All Keys
This example demonstrates how to use the Keys method to return an array of all keys.
Returning the Value of an Item
This example demonstrates how to use the Item property to return the value of an item.
Setting a Key
This example demonstrates how to use the Key property to set a key in a Dictionary object.
Returning the Number of Key/Item Pairs
This example demonstrates how to use the Count property to return the number of key/item pairs.
Dictionary Object
The Dictionary object is used to store information in name/value pairs (equivalent to keys and items). The Dictionary object may seem simpler than an array; however, it is a more satisfactory solution for handling associated data.
Comparing Dictionaries and Arrays:
- Keys are used to identify items in a Dictionary object
- You do not need to call ReDim to change the size of a Dictionary object
- When an item is deleted from a Dictionary, the remaining items move up automatically
- A Dictionary is not multidimensional, while an array can be
- A Dictionary has more built-in functions than an array
- A Dictionary works better than an array when frequently accessing random elements
- A Dictionary works better than an array when locating items by their content
The example below creates a Dictionary object, adds some key/item pairs to it, and then retrieves the item value for the key gr:
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>
Output:
The value of key gr is: Green
The properties and methods of the Dictionary object are described below:
property
| property | Description |
|---|---|
| CompareMode | Sets or returns the comparison mode used to compare keys in the Dictionary object. |
| Count | Returns the number of key/item pairs in the Dictionary object. |
| Item | Sets or returns the value of an item in the Dictionary object. |
| Key | Sets a new key value for an existing key value in the Dictionary object. |
Method
| Method | Description |
|---|---|
| Add | Adds a new key/item pair to the Dictionary object. |
| Exists | Returns a Boolean value indicating whether a specified key exists in the Dictionary object. |
| Items | Returns an array of all items in the Dictionary object. |
| Keys | Returns an array of all keys in the Dictionary object. |
| Remove | Deletes a specified key/item pair from the Dictionary object. |
| RemoveAll | Deletes all key/item pairs from the Dictionary object. |