QTP Supports Dictionary objects which will be used to store data in a Key & Item combination. Dictionary object is one of the feature of VB Script.We can read the Item from the dictionary object using the key. Also, dictionary objects support various operations for storing data effectively. we can even say dictionary objects are another form of dynamic array which becomes more handy than array.
Creating Dictionary Objects:
Dim oDict
Set oDict = CreateObject("scripting.dictionary")
We can create dictionary object using CreateObject method. In the above example oDict is the dictionary object created.
Adding values to Dictionary Object:
oDict.Add "Key1","Item1"
oDict.Add "Key2","Item2"
Read a item from Dictionary Object:
Msgbox oDict.Item("Key1")
Using Item method, we can read the item corresponding to a key.
"Item1" will be retrieved when executing the above line.
Read all items from Dictionary Object:
For each vItem in oDict.Items
msgbox vItem
Next
Removing a key from Dictionary Object:
oDict.Remove ("Key1")
When executing the above the line, the "Key1" key along with it's item will be removed from the Dictionary.
Removing all keys from Dictionary Object:
oDict.RemoveAll
Changing a key in Dictionary Object:
oDict.Key("Key1") = "Key3" 'Set key for Key1 to Key3
Msgbox oDict.Item("Key3")
In the above lines, we are assigning/changing the 'Key1' to 'Key3'. In the Msgbox 'Item1' will be displayed as it's corresponding Key name is changed to 'Key3'.
If you read all the keys from the Dictionary then 'Key3' & 'Key2' will be retrieved and there won't be any key with 'Key1' name as it's changed.
Well, we have already seen how to read all the Items from the dictionary. Here is the script to read all the Keys from the dictionary.
For each vKey in oDict.Keys
msgbox vKey
Next
You are having a question rite? I am able hear that you are asking whether Dictionary objects supports to check if a specific key is present in the dictionary or not. Here is the way to do that..
Msgbox oDict.Exists("Key3") 'It will Return True
Msgbox oDict.Exists("Key1") 'It will Return False
It will return either True/False based on the presence of the Key in the dictionary.
Also, we can get the count of the key/Item pair exists in the dictionary.
Msgbox oDict.Count 'It will Return 2
One more advantange of dictionary object is that we can use any number of dictionary objects in our script and we can have any number of items in the dictionary as well. How easy and useful this dictionary object is!!! Well, we can create nested dictionary object also which we will see in another post.. :)
No comments:
Post a Comment