Summary: Discusses the VBScript Dictionary object.
The VBScript Dictionary object provides an item indexing facility.
The Dictionary object is used to hold a set of data values in the form of (key, item) pairs. A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings. Each key in a single Dictionary object must be unique.
The ProgID for a Dictionary object is “Scripting.Dictionary”, and so the following example creates a Dictionary object:
Dim oDict Set oDict = CreateObject("Scripting.Dictionary")
Dictionary objects have one property that should be set before any data values are stored in the dictionary. There are two modes for the .CompareMode property which control how individual keys are compared. If the mode is vbBinaryCompare (the default), upper and lower case letters in keys are considered distinct. If the mode is vbTextCompare, upper and lower case letters in keys are considered identical. This means that a Dictionary object in binary mode can contain two keys “Key” and “key”, whereas these would be considered the same key in text mode.
To add a value to a Dictionary, use the .Add method. For example:
Dim oDict Set oDict = CreateObject("Scripting.Dictionary") oDict.CompareMode = vbBTextCompare oDict.Add "Pastrami", "Great" oDict.Add "Roast Beef", "OK on Sunday" oDict.Add "Salami", "Not so good"
The first argument to the .Add method is the key value and the second argument is the item value. There is no limit to the number of values that can be added to a dictionary. To remove a value from a dictionary, use the .Remove method and specify the key to remove. For example:
To remove all values and clear the dictionary, use the .RemoveAll method. Use the .Count property to obtain a count of values in the dictionary.
The .Exists method returns True if the specified key exists within the dictionary. For example:
If oDict.Exists("Pastrami") Then Rhino.Print "Pastrami is available today."
To retrieve the item value for a given key, use the .Item property. This is the default property for a Dictionary object. For example:
If oDict.Exists("Salami") Then Rhino.Print oDict("Salami")
Here, the Rhino.Print statement displays the item value stored in the dictionary for the “Salami” key.
Use the .Key property to change the key value for a given key. For example:
oDict.Key("Salami") = "Italian Salami"
The .Keys and .Items methods return an array containing all the keys or items from the dictionary. For example:
aMeats = oDict.Keys aComments = oDict.Items
Dictionaries are frequently used when some items need to be stored and recovered by name. For example, a dictionary can hold all the environment variables defined by the system or all the values associated with a registry key. However, a dictionary can only store one item for each key value. That is, dictionary keys must all be unique.