Tuesday, August 6, 2013

Dictionary object in VBscript

Dictionary Object


Object that stores data key, item pairs.

A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.


Methods:

object.Add --> Adds a key and item pair to a Dictionary object
                     Syntax: Set oDict = CreateObject("Scripting.Dictionary")
                                 oDict.Add "a", "USA"
        oDict.Add "b", "UK"
                                 oDict.Add "c", "Canada"
In the above example, oDict is a dictionary object created and the method "Add" is used to add keys, values to a ditcionary object.
a is the key and USA is the value. The Keys should be unique.

object.Exists --> Takes the key as the parameter and returns a boolean value (true/false).
Syntax: oDict.Exists("a") -- returns true
                                     oDict.Exists("z") -- reurns false.

object.Items --> Returns an array containing all the items in a Dictionary object.
                        Syntax: temp = oDict.Items   'temp is an array 
           For i=0 to ubound(temp)
print temp(i) 'returns USA, UK, Canada
Next

object.Keys --> Returns an array containing all existing keys in a Dictionary object.
          Syntax:  tempKeys = oDict.Keys   'tempKeys is an array of keys
           For i=0 to ubound(tempKeys)
print temp(i) 'returns a, b, c
Next



Properties:

object.Count --> Returns the size/count of the dictionary object.
                        Syntax: oDict.count -- 3 elements.

object.Item -->  Set or Returns an item for a specified key in a Dictionary object.
                       Syntax: oDict.Item("a") -- returns "USA".

***Note***
Just by running the statement - oDict.Item("n") will add an item in the dictionary object, with "n" as the key and value as null/blank.

object.Key -->  Sets a key in a Dictionary object.
                       Syntax: oDict.Key("a") = "z" -- sets the new key, i.e replace "a" with "z"
          print oDict.Exists("a") -- returns false 
                                   print oDict.Exists("n") -- returns true



Sample code:


Retrive key value pair from Dictionary object, using the below methods.

tempKeys = oDict.Keys
For i=0 to ubound(tempKeys)
print tempKeys(i)&" -- "& oDict.Item(tempKeys(i))

Next

No comments:

Post a Comment