Working with dictionary in MS VBScript

What is a dictionary in our context?

Working with dictionary is like working with an array, only easier to work with. It is a place to hold data. Just like an array can be used to hold data in a convenient place for use within the script, a dictionary also holds data.

A dictionary works like a single dimension array. You can store only one column’s worth of data in your dictionary.

Every item stored in dictionary is associated with a key. The key is used to identify the value we would like to store or retrieve from the dictionary. In array we use index number to identify the data but in dictionary we use keys.

Working with dictionary offers a couple of advantages over arrays:

  1. The first advantage is that you can retrieve any value by just knowing the key of it. However, in array you should know the index value.
  2. Dictionary does not require s specific size configuration.

Understanding the dictionary object

To use the VBScript dictionary, you need to first create it. The basic syntax for this is given below:

Set objDictionary = CreateObject("scripting.dictionary")

Adding items to dictionary

After you have created a dictionary, you can add items to it and as you might have just guessed using Add method.

Option Explicit
Dim objDictionary, i
Set objDictionary = CreateObject("scripting.dictionary")
objDictionary.Add 1, "Apple"
objDictionary.Add 2, "Orange"
objDictionary.Add 3, "Banana"
objDictionary.Add 4, "Pear"

In the example above we created a dictionary and assigned it to variable objDictionary. After that we added few items in “key, value” format.


Since we now have some items in our dictionary, let us quickly see how to retrieve them using a for loop.

For i = 1 To 4
   WScript.Echo objDictionary.item (i)

Counting with count

As you have noticed we have used “For i = 1 To 4” in our code above. This means that the For loop will iterate 4 times. We knew that we have 4 items in our dictionary hence we could hard code that.

But what will happen if we add more items to the dictionary?

We will need to change the for loop as well. Sometimes this will not be easy as we would not know the exact number of items in dictionary or the dictionary might keep on increasing.

In such cases we use “objDictionary.count”. Modified For loop will now loo like this:

For i = 1 To objDictionary.count
   WScript.Echo objDictionary.item (i)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *