ASP Dictionary



Dictionary objects are used to store information in name/value pairs.


tryitimg.gif

Try it - Example

Does the key specified exist?
This example demonstrates how to create a Dictionary object and then use the Exists method to check whether the specified key exists.

Return an array of all items
This example demonstrates how to use the Items method to return an array of all items.

Return an array of all keys
This example demonstrates how to use the Keys method to return an array of all keys.

Return the value of an item
This example demonstrates how to use the Item property to return the value of an item.

Set a key
This example demonstrates how to use the Key property to set a key in a Dictionary object.

Return 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

Dictionary objects are used to store information in name/value pairs (equivalent to keys and items). Dictionary objects appear to be simpler than arrays, however, Dictionary objects are a more satisfactory solution for handling related data.

Compare Dictionaries and Arrays:

  • Keys are used to identify items in Dictionary objects

  • You do not need to call ReDim to change Dimensions of Dictionary objects

  • When an item is deleted from a Dictionary, the remaining items are automatically moved up

  • Dictionary is not multi-dimensional, but an array Is multi-dimensional

  • Dictionary has more built-in functions than array

  • Dictionary works better than array when accessing random elements frequently Better

  • #Dictionary works better than arrays when locating items based on their contents

The following example creates a Dictionary object , added some key/item pairs to the object, and then retrieved the item value for 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 as follows:

Properties

Properties Description
CompareMode Sets or returns the comparison mode used to compare keys in a Dictionary object.
Count Returns the number of key/item pairs in the Dictionary object.
Item Sets or returns the value of an item in a Dictionary object.
Key Set 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 the 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 Removes the specified key/item pair from the Dictionary object.
RemoveAll Removes all key/item pairs in the Dictionary object.