This section describes Dictionary object properties and methods. A tutorial example is provided on how to add and remove keys and values into a Dictionary object.
Dictionary: An object representing a collection of pairs of keys and values,
working like an associate array in Perl. It offers the following methods and properties:
"Add key, item": Method to add a pair of key and value to this dictionary.
"Exists(key)": Method to return true if the specified key exists in this dictionary.
"Keys()": Method to return an array containing all the keys in this dictionary.
"Items()": Method to return an array containing all the values in this dictionary.
"Remove(key)": Method to remove a pair of key and value from this dictionary.
"RemoveAll()": Method to remove all pairs of keys and values from this dictionary.
"Item(key)": Property to set or return the value associated with the specified key.
"Count": Property to return the number of pairs of keys and values.
Here is a VBScript example to show you how to use "Dictionary" objects:
<html>
<body>
<!-- dictionary_test.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
' Creating a dictionary object
set user = CreateObject("Scripting.Dictionary")
' Adding a pair of key and item
user.add "FirstName", "Bill"
user.add "LastName", "Smith"
user.add "Email", "bill@com.com"
user.add "Country", "Canada"
' Iterating through the dictionary
n = user.Count
document.writeln("Before - Number of keys: " & n)
keys = user.Keys()
for i=0 to n-1
k = keys(i)
v = user.Item(k)
document.writeln(k & ": " & v)
next
' Modifying the dictionary
user.remove("Country")
user.Item("Email") = "bill@smith.com"
user.Item("Phone") = "123-456-7890"
' Iterating through the dictionary
document.writeln("After - Number of keys: " & n)
keys = user.Keys()
for i=0 to n-1
k = keys(i)
v = user.Item(k)
document.writeln(k & ": " & v)
next
</script>
</pre>
</body>
</html>
Output:
Before - Number of keys: 4
FirstName: Bill
LastName: Smith
Email: bill@com.com
Country: Canada
After - Number of keys: 4
FirstName: Bill
LastName: Smith
Email: bill@smith.com
Phone: 123-456-7890
Note that:
"CreateObject()" method is called to create an empty Dictionary object.
Method with two parameters can not use parentheses to list the parameters, for example,
'user.Add "FirstName", "Bill"'. This is a very strange syntax for experienced programmers,
because all most every other language requires parentheses, no matter how many parameters
there are in a method call.
Property "Item(key)" can be used on the left hand side of an assignment
operator, for example, 'user.Item("Email") = "bill@smith.com"'.
Property "Item(key)" used an assignment statement will force an auto-addition of the
specified key to this dictionary, for example, 'user.Item("Phone") = "123-456-7890"'.