Search This Blog

Tuesday, August 17, 2010

What is Dictionary Object - Overview

Dictionary object allows storing key value pairs. A dictionary object can be used for easy lookup of values. Dictionary is a not a QTP specific functionality and is available in normal VBScript as well.

Creating the Dictionary
A dictionary object can be created using CreateObject for COM class “Scripting.Dictionary”. The code below shows how to create the dictionary object in QTP


'Create the Dictionary Object
Set oDict = CreateObject("Scripting.Dictionary")


Below table shows list of methods that dictionary objects supports.
Method Description
Add (key, item)- Adds a key and item pair to a Dictionary object.
Exists(key)- Returns true if a specified key exists in the Dictionary object, false if it does not
Items() - Returns an array containing all the items in a Dictionary object
Keys() - Returns an array containing all existing keys in a Dictionary object.
Remove(key) - Removes a key, item pair from a Dictionary object
RemoveAll() - The RemoveAll method removes all key, item pairs from a Dictionary object.

Count - Returns the number of items in a Dictionary object. Read-only.
Item Sets or returns an item for a specified key in a Dictionary object. Read/write
Key(Key) Sets a key in a Dictionary object.

Adding Items to Dictionary:
There are two ways to Add items to dictionary. One is to use the Add method and another is to use the Item property. Both the methods are shown in code below
'Method 1 for Adding items to dictionary
'Add items to dictionary
oDict.Add "CA", "California"
oDict.Add "LA", "Los Angeles"

'The below line will throw an error as LA key already exist
oDict.Add "LA", "Los Angeles 2"

'Method 2 for adding items to dictionary
oDict.Item("CA") = "California"

'Item is the default property so ".Item" is not required
oDict("LA") = "Los Angeles"

'No Error this time as we are actually using the
'Item property and not the Add method
oDict("LA") = "Los Angeles 2"100 Miles From Memphis