Dictionary Object |
Createable
Yes
Library
Microsoft Scripting Runtime
Description
The Dictionary object is similar to a Collection object, except that it's loosely based on the Perl associative array. Like an array or a Collection object, the Dictionary object holds elements, called items or members, containing data. A Dictionary object can contain any data whatsoever, including objects and other Dictionary objects. Access the value of these dictionary items by using unique keys (or named values) that are stored along with the data, rather than by using an item's ordinal position as you do with an array. This makes the Dictionary object ideal when you need to access data that is associated with a unique named value.

You can access each item stored to a Dictionary object by using the For Each ...Next construct. However, rather than returning a variant containing the data value stored to the Dictionary object as you would expect, it returns a variant containing the key associated with the member. You then have to pass this key to the Item method to retrieve the member, as the following example shows:

    Dim vKey
    Dim sItem, sMsg
    Dim oDict

    Set oDict =  CreateObject("Scripting.Dictionary")
    oDict.Add "One", "Engine"
    oDict.Add "Two", "Wheel"
    oDict.Add "Three", "Tire"
    oDict.Add "Four", "Spanner"

    For Each vKey In oDict
       sItem = oDict.Item(vKey)
       sMsg = sMsg & sItem & vbCrLf
    Next

    MsgBox sMsg

Dictionary Object Properties
The Dictionary object includes the following four properties:

Property | Description
CompareMode | Determines the order of text comparisons in the Item property
Count | Indicates the total number of items in the dictionary
Item | Sets or retrieves a particular item of data in the dictionary
Key | Renames an existing key

Dictionary Object Methods
The Dictionary object supports the following five methods:

Property | Description
Add | Adds an item and its associated key to the dictionary
Exists | Determines whether a particular key exists in the dictionary
Keys | Returns all keys in the dictionary
Remove | Removes an item from the dictionary
Remove All | Removes all the data from the dictionary

Dictionary.Add Method |
Syntax
    dictionaryobject.Add key, item

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

key

  Use: Required

  Data Type: Any

  A key value that's unique in the Dictionary object.

item

  Use: Required

  Data Type: Any

  The item to be added to the dictionary.

Description
Adds a key and its associated item to the specified Dictionary object.
Rules at a Glance

- If the key isn't unique, runtime error 457, "This key is already associated with an element of this collection," is generated.

- item can be of any data type, including objects and other Dictionary objects.

Example
The example uses a Dictionary object to store state abbreviations and their corresponding state names:
    Dim StateCode, StateName
    Dim StateDict
    Dim Key

    Set StateDict = CreateObject("Scripting.Dictionary")

    StateCode = "CA"
    StateName = "California"
    StateDict.Add StateCode, StateName

    StateCode = "NY"
    StateName = "New York"
    StateDict.Add StateCode, StateName

    StateCode = "MI"
    StateName = "Michigan"
    StateDict.Add StateCode, StateName

    Key = "NY"
    MsgBox StateDict.Item(Key)
Programming Tips and Gotchas

- The order of members within a Dictionary object is officially undefined. That is, you can't control the position of individual members, nor can you retrieve individual members based on their position within the Dictionary object. Your code, in short, should make no assumptions about the position of individual elements within the Dictionary objects.

- Once you add a key and its associated data item, you can change the key by using the write-only Key property.

- Use the Dictionary object to store tables of data, and particularly to store single items of data that can be meaningfully accessed by a key value.

- The use of the Dictionary object to store multifield data records is not recommended; instead, classes offer a better programmatic alternative. Typically, you would store a record by adding an array representing the record's field values to the dictionary. But assigning arrays to items in the Dictionary object is a poor programming practice, since individual elements of the array cannot be modified directly once they are assigned to the dictionary.

See Also
Dictionary.Key Property

Dictionary.CompareMode Property |
Data Type
Long
Description
Sets or returns the mode used to compare the keys in a Dictionary object.
Rules at a Glance

- CompareMode can be set only on a dictionary that doesn't contain any data.

- The CompareMode property can have either of the following two values:

  0, Binary

- This is the default value. It compares the keys with a string byte-per-byte to determine whether a match exists.

  1, Text

    Uses a case-insensitive comparison when attempting to match keys with a string.

  In addition, the value of CompareMode can be greater than 2, in which case it defines the locale identifier (LCID) to be used in making the comparison.

Programming Tips and Gotchas

- You need to explicitly set the CompareMode property only if you do not wish to use the default binary comparison mode.

- The Scripting Runtime type library defines constants (BinaryCompare and TextCompare) that can be used in place of their numeric equivalents. You can do this in one of three ways. You can define the constants yourself by adding the following code to your script:

      Const BinaryCompare = 0
      Const TextCompare = 1

  You can also use the equivalent vbBinaryCompare and vbTextCompare constants that are defined in the VBScript library.

  Finally, if you're an ASP programmer, you can use the METADATA directive to access the Scripting Runtime type library; if you're developing a Windows Script Host script, you can include the following line in a Windows Script Host (.wsf ) file in order to access the constants from the Scripting Runtime type library:

      <reference GUID="{420B2830-E718-11CF-893D-00A0C9054228}" />

- Practically, the CompareMode property indicates whether the comparison between existing key names and the key argument of the Dictionary object's Add method, Exists method, Item property, or Key property will be case-sensitive (BinaryCompare) or case-insensitive (TextCompare). By default, comparisons are case-sensitive.

Dictionary.Count Property |
Data Type
Long
Description
A read-only property that returns the number of key/item pairs in a Dictionary object.
Rules at a Glance
This property returns the actual number of items in the dictionary. So if you use the Count property to iterate the items in the dictionary, you would use code like the following:
    Dim ctr
    For ctr = 0 to dictionary.Count - 1
       ' do something
    Next

Dictionary.Exists Method |
Syntax
    dictionaryobject.Exists(key)

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

key

  Use: Required

  Data Type: String

  The key value being sought.

Return Value
Boolean
Description
Determines whether a given key is present in a Dictionary object.
Rules at a Glance
Returns True if the specified key exists in the Dictionary object; False if not.
Programming Tips and Gotchas

- If you attempt to use the Item property to return the item of a nonexistent key, or if you assign a new key to a nonexistent key, the nonexistent key is added to the dictionary, along with a blank item. To prevent this, you should use the Exists property to ensure that the Key is present in the dictionary before proceeding.

- The way in which key is compared with the existing key values is determined by the setting of the Dictionary object's CompareMode property.

Example
    If oDict.Exists(strOldKey) Then
        oDict.Key(strOldKey) = strNewKey
    End If

Dictionary.Item Property |
Syntax
The syntax for setting an item is:
    dictionaryobject.Item(key) = item
The syntax for returning an item is:
    value = dictionaryobject.Item(key)

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

key

  Use: Required

  Data Type: String

  A unique string key for this Dictionary object.

item

  Use: Optional

  Data Type: Any

  The data associated with key.

Data Type
Any
Description
Sets or returns the data item to be linked to a specified key in a Dictionary object.
Rules at a Glance

- The Item property is the default member of the Dictionary object.

- The data type is that of the item being returned.

- Unlike the Item property of most objects, the Dictionary object's Item property is read/write. If you try to set item to a nonexistent key, the key is added to the dictionary, and the item is linked to it as a sort of "implicit add."

Programming Tips and Gotchas

- The Dictionary object doesn't allow you to retrieve an item by its ordinal position.

- If you provide a nonexistent key when trying to retrieve an item, the dictionary exhibits rather strange behavior: it adds key to the Dictionary object along with a blank item. You should therefore use the Exists method prior to setting or returning an item, as the example shows.

- If the item to be assigned or retrieved from the Dictionary object is itself an object, be sure to use the Set keyword when assigning it to a variable or to the Dictionary object.

- The comparison of key with member keys is defined by the value of the Dictionary object's CompareMode property.

- Although the read/write character of the Dictionary object's Item property has its drawbacks, it also has its advantages. In particular, it makes it easy to overwrite or replace an existing data item, since its Item property is read/write: simply assign the new value like you would with any other property.

- The Dictionary object should never be used to store HTML form or query data in Session scope in an ASP application. Since the Dictionary object is an apartment-threaded COM object, this has the effect of locking down the application to a single thread of execution.

Example
The example uses the Dictionary object as a lookup table to retrieve the state name that corresponds to the state code entered by the user. The HTML page that submits user information to the server is as follows:
    <HTML>
    <HEAD><TITLE>Dictionary Object Example</TITLE></HEAD>
    <BODY>
    Enter your name and location: <P>
    <FORM METHOD=POST ACTION=dictobj.asp>
    Your name:
    <INPUT TYPE="Text" NAME="VisitorName" /><P>
    Your location:
    <INPUT TYPE="Text" NAME="City" />,
    <INPUT TYPE="Text" NAME="State" SIZE=2 /> <P>
    <INPUT TYPE="Submit" VALUE="Submit" />
    </FORM>
    <BODY>
    </HTML>
The ASP page that retrieves the information submitted by the user, encodes it, and uses the Dictionary object to retrieve the full state name is as follows:
    <HTML>
    <HEAD>
    <TITLE>ASP Page for the Dictionary Object Example</TITLE>
    </HEAD>
    <BODY>

                <% Show Greeting %>

    <SCRIPT LANGUAGE="VBScript" RUNAT="Server">

    Sub ShowGreeting(  )
       Dim StateDict
       Dim ClientName, ClientState

       ' Initialize dictionary
    Set StateDict = Server.CreateObject("Scripting.Dictionary")
    StateDict.Add "NY", "New York"
    StateDict.Add "CA", "California"
    StateDict.Add "FL", "Florida"
    StateDict.Add "WA", "Washington"
    StateDict.Add "MI", "Michigan"
    StateDict.Add "MA", "Massachusetts"
    StateDict.Add "MN", "Minnesota"
    ' add other states

    ClientName = Server.HTMLEncode(Request.Form("VisitorName"))
    ClientState = Server.HTMLEncode(Request.Form("State"))

    Response.Write("Hello, " & ClientName & ". <P>")
    Response.Write("We are pleased to have a visitor from ")
       Response.Write(StateDict.Item(ClientState) & "!")
    End Sub
    </SCRIPT>
    </BODY>
    </HTML>

Dictionary.Items Method |
Syntax
    dictionaryobject.Items

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

Return Value
A Variant array.
Description
Returns an array containing all the items in the specified Dictionary object.
Rules at a Glance
The returned array is always a zero-based variant array whose data type matches that of the items in the Dictionary object.
Programming Tips and Gotchas

- The only way to directly access members of the Dictionary is via their key values. However, using the Items method, you can "dump" the data from the Dictionary into a zero-based variant array. The data items can then be accessed like an array in the normal way, as the following code shows:

      Dim vArray
      vArray = DictObj.Items
      For i = 0 to DictObj.Count -1
          Response.Write vArray(i) & "<P>"
      Next I

- The Items method retrieves only the items stored in a Dictionary object; you can retrieve all the Dictionary object's keys by calling its Keys method.

See Also
Dictionary.Keys Method

Dictionary.Key Property |
Syntax
    dictionaryobject.Key(key) = newkey

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

key

  Use: Required

  Data Type: String

  The key of an existing dictionary item.

newkey

  Use: Required

  Data Type: String

  A new unique key for this dictionary item.

Data Type
A String.
Description
Replaces an existing key with a new one.
Rules at a Glance

- The Key property is write-only.

- key, the existing key value, must exist in the dictionary or an error results.

- newkey must be unique and must not already exist in the dictionary or an error results.

- The comparison of key and newkey with existing key values is defined by the Dictionary object's CompareMode property.

Example
    Private Function ChangeKeyValue(sOldKey, sNewKey)
    'Assumes oDictionary is a public object
        If oDictionary.Exists(sOldKey) Then
            oDictionary.Key(sOldKey) = sNewKey
            ChangeKeyValue = True
        Else
            ChangeKeyValue = False
        End If
    End Function
Programming Tips and Gotchas

- Use the Key property to change the name of an existing key. Use the Add method to add a new key and its associated value to the Dictionary object. Use the Keys method to retrieve the names of all keys; this is especially useful when you don't know the names or the contents of the dictionary in advance.

- Attempting to retrieve the key name (a nonsensical operation, since this amounts to providing the key's name in order to retrieve the key's name) generates an error, as does attempting to modify a key name that hasn't already been added to the dictionary.

- Using a For Each...Next loop to iterate the members of a Dictionary object involves an implicit call to the Key property. In other words, each iteration of the loop returns a key, rather than a data item. To retrieve the member's data, you then must use its key value to access its data through the Item property. This is illustrated in the example for the Dictionary.Item property.

Dictionary.Keys Method |
Syntax
    dictionaryobject.Keys

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

Return Value
An array of strings.
Description
Returns an array containing all the Key values in the specified Dictionary object.
Rules at a Glance
The returned array is always a 0-based variant array whose data type is String.
Programming Tips and Gotchas
The Keys method retrieves only the keys stored in a Dictionary object. You can retrieve all the Dictionary object's items by calling its Items method. You can recall an individual data item by using the Dictionary object's Item property.
Example
    Dim vArray
    vArray = DictObj.Keys
    For i = 0 to DictObj.Count -1
        Response.Write vArray(i) & "<BR>"
    Next

Dictionary.Remove Method |
Syntax
    dictionaryobject.Remove key

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

key

  Use: Required

  Data Type: String

  The key associated with the item to be removed.

Description
Removes both the specified key and its associated data (i.e., its item) from the dictionary.
Rules at a Glance
If key doesn't exist, runtime error 32811, "Element not found," occurs.

Dictionary.RemoveAll Method |
Syntax
    dictionaryobject.RemoveAll

dictionaryobject

  Use: Required

  Data Type: Dictionary object

  A reference to a Dictionary object.

Description
Clears out the dictionary; in other words, removes all keys and their associated data from the dictionary.
Programming Tips and Gotchas
If you want to remove a selected number of members rather than the entire contents of the dictionary, use the Remove method.