Example scenarios for working with Dictionary Object Using vbscript. – User friendly Tech help
Every day you wake up is a victory. Learn more and share more….
n
nConcept 1:-How to find the occurrence count of item in a given sample?
n
nn
Using dictionary object we would find the count of occurrence of given value in the sample.
n
Example: – we need to find the “Help” words in the given string say: – “God help those who help themselves”
n
You can also refer the difference between dictionary andarray.
n
nLets connect for more updates at Fb,G+,Twitter.n
Code:-
n
n
'Input String
sSample = "God help those who help themselves"
'Splitting the given stringarrSample = Split(sSample)
'Calling the function to get the Count of all the items
Set objCount = fn_Count(arrSample)arrKey = objCount.Keys
For iRun = 0 To objCount.Count - 1
MsgBox "Count of '" & arrKey(iRun) & "' =" & objCount.Item(arrKey(iRun))
Next
'*******************************************Function*********************************
'Function Name:- fn_Count
'Function Description:- Function find the occuerence of given word in the string
'Input Parameters:- Given String
'Output Parameters:- Dictionary object
'************************************************************************************
Function fn_Count(arrSample)
Dim iRow, iItem
Dim objDic
Set objDic = CreateObject("scripting.dictionary")
'Looping through array
For iRow = LBound(arrSample) To UBound(arrSample) iItem = arrSample(iRow)
If Not objDic.Exists(iItem) Then
objDic.Add iItem, 1
Else
objDic.Item(iItem) = objDic.Item(iItem) + 1
End If
Next
Set fn_Count = objDic
End Function
n
Concept 2:- How to sort items in the given dictionary?
n
Note: – we can sort dictionary keys in the same manner as we did items.
n
Code:-
n
'*******************************************Function*********************************
'Function Name:- fn_SortDictionary
'Function Description:- Function to sort the items in the given dictionary
'Input Parameters:- Unsorted Dictionary object
'Output Parameters:- Sorted Dictionary object
'************************************************************************************
Function fn_SortDictionary(objdict)
Dim i, j, temp
For Each i In objdict
For Each j In objdict
If (objdict.Item(i)