Arrays are the first construct that VBScript instructors introduce when they discuss how to group data. With arrays, you can store columns of data in one place, then access the data later through one variable. However, years of real-world use have revealed that arrays aren't always the most desirable solution to gather and maintain related data. Fortunately, a new type of array has emerged: the dictionary. Here's a look at what dictionaries are and how you manipulate them with the methods and properties that Table 1 shows.
Comparing Dictionaries and Arrays
A dictionary is a general-purpose data structure that looks like a linked list but acts like a "super array." Like VBScript arrays, dictionaries store data and make that data available through one variable. (If you're unfamiliar with VBScript arrays, see my July 1999 column.) However, dictionaries differ from arrays in many ways, including
- A dictionary has additional methods to add new items and check for existing items.
- You don't need to call ReDim to extend the dictionary's size.
- When you delete a particular item from a dictionary, all the subsequent items automatically shift up. For example, if you delete the second item in a three-item dictionary, the original third item automatically shifts up into the second-item slot.
- You use keys to identify dictionary items. Keys can be any data subtype, except an array or dictionary.
- A dictionary can't be multidimensional. (Although you can't store arrays or dictionaries in a dictionary item, you can store dictionaries in array items.)
The most important reason for using a dictionary instead of an array is that a dictionary is more flexible and is richer in terms of built-in functionality. Dictionaries work better than arrays when you need to access random elements frequently. Dictionaries also work better when you want to locate items by their content rather than their position. . . .
<br>
Dim d1, d2 As Dictionary<br>
Dim array1(3, 3) As String<br>
Dim x, y As Long<br>
Set d1 = New Dictionary<br>
For x = 1 To 3<br>
Set d2 = New Dictionary<br>
d2.Add CStr(x), "value" & CStr(x)<br>
d1.Add CStr(x), d2<br>
Next x<br>
Debug.Print d1("1")("1")
For x = 1 To 3<br>
For y = 1 To 3
array1(x, y) = CStr(x) & " " & CStr(y)<br>
Next y<br>
Next x<br>
For x = 4 To 6<br>
d1.Add CStr(x), array1<br>
Next x<br>
Debug.Print d1("6")(3, 3)<br>
Set d2 = Nothing<br>
Set d1 = Nothing<br>
Erase array1<br>
<br>
The output is:<br>
value1<br>
3 3</p>
David Doucette August 04, 2002