Search code examples
arraylistvbscriptscripting.dictionary

How do I append to an array that is a value of a key in a dictionary?


If I set up a dictionary as such:

set myDict = CreateObject("Scripting.Dictionary")

I ask a user his name.

Wscript.StdOut.WriteLine "What is your name: "
name = Wscript.StdIn.ReadLine

I then ask the user for five numbers.

Wscript.StdOut.WriteLine "Enter a number: "
    num1 = cint(Wscript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter a number: "
    num2 = cint(Wscript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter a number: "
    num3 = cint(Wscript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter a number: "
    num4 = cint(Wscript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter a number: "
    num5 = cint(Wscript.StdIn.ReadLine)

and place the five prompted numbers into any array using ArrayList

Set myArrayList = CreateObject( "System.Collections.ArrayList" )
myArrayList.Add num1
myArrayList.Add num2
myArrayList.Add num3
myArrayList.Add num4
myArrayList.Add num5

If I add a key with name in the dictionary that I set up.

myDict.Add name

Can I add myArrayList as a value to name in the myDict dictionary I previously set up.

and if so,how can I append or add to myArrayList if I were to loop the five number questions?


Solution

  • The value of a dictionary can be a primitive value as well as an array or an object (like an ArrayList), either like this:

    myDict.Add name, myArrayList
    

    or like this:

    Set myDict(name) = myArrayList
    

    You can work with the object by selecting it by name. The following would append the value 42 as a new element to the array list:

    myDict(name).Add 42
    

    You could also put a new (empty) array list into the dictionary and append your numbers afterwards:

    Set myDict(name) = CreateObject("System.Collections.ArrayList")
    Wscript.StdOut.WriteLine "Enter a number: "
    myDict(name).Add CInt(WScript.StdIn.ReadLine)
    ...