Adding Key-Item Pairs to a Dictionary

Microsoft® Windows® 2000 Scripting Guide

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

  • Key name

  • Item value

For example, the script in Listing 4.45 creates a Dictionary object and then adds the key-item pairs shown in Table 4.10.

Table 4.10 Sample Key-Item Pairs

Key

Item

Printer 1

Printing

Printer 2

Offline

Printer 3

Printing

Listing 4.45 Adding Key-Item Pairs to a Dictionary

  
1
2
3
4
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

Dictionary keys must be unique. For example, the following two script statements will generate a run-time error because, after the first line is interpreted, the key "Printer 1" will already be in the Dictionary:

objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 1", "Offline"

Inadvertently Adding a Key to a Dictionary

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 nonexistent 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 nonexistent item, Printer 4:

Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Wscript.Echo objDictionary.Item("Printer 4")

When the script tries to echo the value of the nonexistent item, no run-time error occurs. Instead, the new key, Printer 4, is added to the Dictionary, along with the item value Null. As a result, the message box shown in Figure 4.9 appears.

Figure 4.9 Message Resulting from Inadvertently Adding a Key to a Dictionary

sas_scr_09s

To avoid this problem, check for the existence of a key before trying to access the value of the item.