A Scripting Dictionary is basically a combination of a database and an array all in one. It uses unique key to identify a corresponding value.
This tutorial is going to cover how to add, update, remove, and get information from the dictionary object.
First we need to create our dictionary object.
Code:
<%
Set objSD = Server.CreateObject("Scripting.Dictionary")
This is how you add items to the dictionary. The first value is the
key and the second value is the
item you are wanting to store. When using the dictionary object, the
key must be unique for that dictionary, otherwise it wil throw an error.
Code:
objSD.Add("Key1", "Value1")
objSD.Add("Key2", "Value2")
objSD.Add('Key3", "Value3")
This code block does a couple different things. First it checks to see if the key exsists in the dictionary. If the key does exsists, it will write the value to the page, if not it will write 'Key Does Not Exsist!'.
Code:
For i = 1 to 4
If objSD.Exsists("Key" & i) Then
Response.Write(objSD.Item("Key" & i))
Else
Response.Write("Key Does Not Exsist!")
End If
Next
This section shows how to update an item in the dictionary. This is fairly straight forward and works like setting any other variable.
Code:
For i = 1 to objSD.Count
objSD.Item("Key" & i) = "ChangedValue" & i
Next
Finally this is how to remove a key from the dictionary. It is a good idea to check that the key you wish to remove is in the dictionary, otherwise the remove statement will throw an error.
Code:
If objSD.Exsists("Key2") Then
objSD.Remove("Key2")
End If
I hope you now see why I like dictionaries because of all the things you can do with them. You can also set your dictionary equal to a session variable. This is
NOT recommended in most instances because dictionaries can take up a lot of memory depending on how big they are and if you have Visual Studio 6 installed, you will not be able to do this because of a setting it makes.
Below this the entire code for easy reference. Happy Scripting
Code:
<%
'Code Written by Ryan Wischmeyer, Indianapoils, IN
Set objSD = Server.CreateObject("Scripting.Dictionary")
objSD.Add("Key1", "Value1")
objSD.Add("Key2", "Value2")
objSD.Add('Key3", "Value3")
For i = 1 to 4
If objSD.Exsists("Key" & i) Then
Response.Write(objSD.Item("Key" & i))
Else
Response.Write("Key Does Not Exsist!")
End If
Next
For i = 1 to objSD.Count
objSD.Item("Key" & i) = "ChangedValue" & i
Next
If objSD.Exsists("Key2") Then
objSD.Remove("Key2")
End If
Set objSD = Nothing
%>
Tutorial Written by
Ryan Wischmeyer, 2004
Indianapois, IN