Everything about Dictionary Object

15
3646
Dictionary Object

Dictionary Object

Most of the time; We use variables, when we need to store a input value or a value retrieved from an outside source. When there are many such values, either we use individual variables or we can store in an array. Alternatively, information can also be stored in a Dictionary object. It is a part of VB Script and so it can be used with the tools supporting VBS.

The Dictionary object is used to hold a set of data values in the form of (key, item) pairs. A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings. Each key in a single Dictionary object must be unique.

A Dictionary object can contain any data including objects and other Dictionary objects. The value of these dictionary items can be accessed by using unique keys that are stored along with the data, rather than by using an item’s ordinal position as you do with an array. This makes the Dictionary object ideal when you need to access data that is associated with a unique named value.

 

Adding Keys and Items

Dictionary is a COM objects, it can be instantiated in the same way as any other COM Object. The ProgID for a Dictionary object is “Scripting.Dictionary”, and so the following example creates a Dictionary object using CreateObject:

Dim oDict
Set oDict = CreateObject("Scripting.Dictionary")

One you have created an instance of the Dictionary object, you can use the Add method to add items to the dictionary. The Add method requires two parameters, which must be supplied in the following order and separated by a comma.

for example

Key Value
Book1 QTP Unplugged
Book2 QTP DP Unplugged
Book3 UFT & QTP Interview Unplugged

Dictionary keys must be unique. In the examples below, after the first line is interpreted, the key “Book1” will already be in the Dictionary.

Set oDict = CreateObject("Scripting.Dictionary")
oDict.Add "Book1", "QTP Unplugged"
oDict.Add "Book2", "QTP DP Unplugged"
oDict.Add "Book3", "UFT & QTP Interview Unplugged"

 

To retrieve the value from dictionary created, we can use .item method of dictionary object.

oDict.item("Book2")

 

One potential problem in using the Dictionary object is that any attempt to reference an element that is not contained in the Dictionary does not result in an error. Instead, the non-existent element is added to the Dictionary. Consider the following script sample, which creates a Dictionary, adds three key-item pairs to the Dictionary, and then attempts to echo the value of a non-existent item, Book4:

Set oDict = CreateObject("Scripting.Dictionary")
oDict.Add "Book1", "QTP Unplugged"
oDict.Add "Book2", "QTP DP Unplugged"
oDict.Add "Book3", "UFT & QTP Interview Unplugged"
MsgBox oDict.Item("Book4")

 

When the script tries to output the value of the nonexistent item, no run-time error occurs. Instead, the new key, Book4, is added to the Dictionary, along with the item value Null.

To avoid this problem, check for the existence of a key before trying to access the value of the item. you can do so using .exists method.

Set oDict = CreateObject("Scripting.Dictionary")
oDict.Add "Book1", "QTP Unplugged"
oDict.Add "Book2", "QTP DP Unplugged"
oDict.Add "Book3", "UFT & QTP Interview Unplugged"
if oDict.Exists("Book4") then msgbox oDict.Item("Book4")

 

Looping through the Items in Dictionary Object

Each item stored in a Dictionary object can be accessed by using For Each statements as shown in the snippet below –

Dim oItem
Dim sItem, sMsg
Dim oDict

Set oDict = CreateObject("Scripting.Dictionary")

Set oDict = CreateObject("Scripting.Dictionary")
oDict.Add "Book1", "QTP Unplugged"
oDict.Add "Book2", "QTP DP Unplugged"
oDict.Add "Book3", "UFT & QTP Interview Unplugged"

For Each oItem In oDict
  sItem = oDict.Item(oItem )
  sMsg = sMsg & sItem & vbCrLf
Next

MsgBox sMsg

 

Configuring Dictionary Properties 

The Dictionary object has only one configurable property, Compare Mode, which plays an important role in determining which keys can be added and which ones cannot.

By default, a Dictionary is created in binary mode, which means each key in the Dictionary is based on its ASCII value. This is important because the ASCII value of an uppercase letter is different from the ASCII value of that same lowercase letter. In binary mode, both of these services can be added to the Dictionary as individual keys. So we can have same keys for multiple Items when in binary mode. for example, book and BOOK

When a Dictionary is configured in text mode, uppercase and lowercase letters are treated identically.

To configure the Dictionary mode, create an instance of the Dictionary object and then set the CompareMode property to one of the following values:

• 0 – Sets the mode to binary. This is the default value.

• 1 – Sets the mode to text.

Set oDict = CreateObject("Scripting.Dictionary")
oDict.CompareMode = 1

You cannot change the CompareMode property of a Dictionary if that Dictionary contains any elements. This is because the binary mode allows you to differentiate between keys based solely on uppercase and lowercase letters. In text mode, however, these three keys are considered identical. If you had these elements in a binary Dictionary and were able to reconfigure that Dictionary in text mode, the Dictionary would suddenly contain three duplicate keys, and it would fail. If you must reconfigure the Dictionary mode, you first need to remove all items from the Dictionary.

 

Manipulating Keys and Items in a Dictionary

By itself, a Dictionary is of little use; a Dictionary is valuable only when you can access, enumerate, and modify the keys and items within that Dictionary. After you have created a Dictionary, you will probably want to do such things as:

• Determine how many key-item pairs are in that Dictionary.

• Enumerate the keys and/or items within the Dictionary.

• Determine whether or not a specific key exists in the Dictionary.

• Modify the value of a key or an item in the Dictionary.

• Remove key-item pairs from the Dictionary.

To remove a value from a dictionary, use the .Remove method and specify the key to remove. For example:

oDict.Remove “Book2”

To remove all values and clear the dictionary, use the .RemoveAll method. Use the .Count property to obtain a count of values in the dictionary.

The .Keys and .Items methods return an array containing all the keys or items from the dictionary. For example:

aBooks = oDict.Keys
aNames = oDict.Items

 

Enumerating a Dictionary

Items and Keys method returns the array of Items and keys respectively. These methods cannot be directly used to access the values, there return array has to be first assigned to a variable and then accessed. Below example illustrates the enumerations.

'Create the dictionary object
Set oDict = CreateObject("Scripting.Dictionary")
oDict.Add "Book1", "QTP Unplugged"
oDict.Add "Book2", "QTP DP Unplugged"
oDict.Add "Book3", "UFT & QTP Interview Unplugged"

aItems = oDict.Items

'Print all the items in the dictionary
For i = LBound(aItems) To UBound(aItems)
    Print aItems(i)
Next

'Print all keys in the dictionary
'We can use For each loop also to access the array
aKeys = oDict.Keys
For Each Key in aKeys
    Print "Key - " & Key
    Print "Value - " & oDict(Key)
Next

 

Use of Dictionary Objects 

Generally dictionaries are used when items need to be stored and recovered by name. For example, a dictionary can hold all the environment variables defined by the system or you have some configuration values for the script which you want to be accessed through out your script scope.

Here is nice

A very simple answer for “when should we use dictionary object?” would be “use dictionary object, when you need find value by key”

As Reserved Object in QTP/UFT

You can add dictionary as a reserved object in QTP/UFT , follow the steps below

  1. Open registry editor through windows run window (type regedit)
  2. Browse to HKEY_CURRENT_USER\Software\Mercury Interactive\QuickTest Professional\MicTest\ReservedObjects
  3. Create a new key under this key with Name as “Dictionary” and as String value “ProgID” with data as “Scripting.Dictionary” as shown in below snapshot.

regeditReservedWords

Start QTP, type “Dictionary.”, it should show the methods and properties of dictionary objects to use.

Dictionary

Sorting a Dictionary

Below function demonstrate, how we can sort a dictionary with items. [Source]

Const dictKey  = 1
Const dictItem = 2

Function SortDictionary(objDict,intSort)
  ' declare our variables
  Dim strDict()
  Dim objKey
  Dim strKey,strItem
  Dim X,Y,Z

  ' get the dictionary count
  Z = objDict.Count

  ' we need more than one item to warrant sorting
  If Z > 1 Then
    ' create an array to store dictionary information
    ReDim strDict(Z,2)
    X = 0
    ' populate the string array
    For Each objKey In objDict
        strDict(X,dictKey)  = CStr(objKey)
        strDict(X,dictItem) = CStr(objDict(objKey))
        X = X + 1
    Next

    ' perform a a shell sort of the string array
    For X = 0 to (Z - 2)
      For Y = X to (Z - 1)
        If StrComp(strDict(X,intSort),strDict(Y,intSort),vbTextCompare) > 0 Then
            strKey  = strDict(X,dictKey)
            strItem = strDict(X,dictItem)
            strDict(X,dictKey)  = strDict(Y,dictKey)
            strDict(X,dictItem) = strDict(Y,dictItem)
            strDict(Y,dictKey)  = strKey
            strDict(Y,dictItem) = strItem
        End If
      Next
    Next

    ' erase the contents of the dictionary object
    objDict.RemoveAll

    ' repopulate the dictionary with the sorted information
    For X = 0 to (Z - 1)
      objDict.Add strDict(X,dictKey), strDict(X,dictItem)
    Next

  End If

End Function

 

15 COMMENTS

    • One approach would be to add each list items into dictionary as key. Since key does not allow duplicates, you will get the duplicate values.
      Another approach would be to check if the item already exists in the dictionary using dictobj.exists. If already exists then it’s duplicate.

  1. Hello Saket,

    I have a question regarding dictionary object,
    I have an array which does not have unique data, how can i convert it to in dictionary

  2. HI,

    How to get multiple query’s data from database , set into dictionary objects and compare dictionary object data with excel data(expected) .

    Please send me the script.

    Thanks in Advance

  3. Hello Friends,

    Is there any way to find if an item exists in a Dictionary object without iterating keys/items ?

    We can use Exists() method for keys, not for items. Please confirm.

    Please let me know your thoughts on it.

    Thanks and regards,
    Divyang

    • here you go, can use of Filter method to find out.

      Set oDict=CreateObject("Scripting.Dictionary")
      oDict.Add "P1","Test123"
      oDict.Add "P2","Testss"
      oDict.Add "P3","Test211"
      oDict.Add "P4","Test3232323232"
      oDict.Add "P5","Testss"

      arr=oDict.Items()

      Ele=Filter(arr,"Testss")
      If UBound(Ele)>-1 Then
      msgbox "Found"
      Else
      msgbox "Not Found"
      End If

  4. I would also like to know how i can find a key using item value?

    For example, i have an item “test” in a Dictionary object and i want to find the key for item “test”.

    Your suggestions are welcome.It would be a great help to me.

    Thanks and regards,
    Divyang

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.