How to Address Arrays With String Indexes

  January 09, 2007

Arrays are an essential part of scripting, but integer indexes aren't very descriptive, for example, testdata[1], testdata[2], testdata[3], ... There's another way you can address the elements of the array that you might find easier to use. In this post I'll explain how to apply the Dictionary object from the Microsoft Scripting Runtime Library, Scrrun.dll.

A Dictionary object contains a set of key-item pairs. A dictionary’s item is a value that is unambiguously associated with a unique key, so that we use the key to retrieve the item. The key can be of any type except a variant or an array but generally it's a string or an integer. The item can be of any type: integer, real, string, variant, object and so on.

You cannot use string indexes in arrays, but you can apply a Dictionary object in its place, and use string keys to access the dictionary items.

The dictionary object has some benefits over basic arrays:

  • The size of the Dictionary object can be set dynamically.
  • Dictionaries surpass arrays in locating items by their content.
  • Dictionaries work better than arrays when accessing random elements frequently.
  • The object has built-in methods and properties that allow users to manage the dictionary’s contents and keys.
  • When deleting an item from a Dictionary, the remaining items are automatically shifted up.

The only disadvantage of dictionaries when compared to arrays, is that they cannot be multidimensional.

The tables below list the methods and properties of the Dictionary object:

Method Description
Add Adds the key-item pair to the object.
Exists Verifies whether the element with the specified key exists.
Items Returns an array that only holds the dictionary’s values without the associated keys.
Keys Returns an array that only holds the dictionary’s keys without the associated values.
Remove Removes the dictionary’s element specified by a key.
RemoveAll Removes all elements from the dictionary.

Property Description
Count Returns the current number of elements in the dictionary.
Item Returns or sets the dictionary’s item that is associated with the specified key.
Key Defines a new key-value to the specified key.
CompareMode Specifies the mode for comparing string keys. The possible values are: 0 - binary (default), 1 - text and 2 - database.

We create the Dictionary object like any other COM object.

The following code sample demonstrates how to use the Dictionary object to address the stored item with the string key.