Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why is the Dictionary.Count incrementing here?

Status
Not open for further replies.

tcspine

IS-IT--Management
Jan 2, 2008
31
US
On Line 42 where it says
"WScript.Echo "The count after using the second for ... next loop Is " & objDictionary.Count"
objDictionary.count gets incremented by 1. Does anyone know why this is happening?

Option Explicit
Dim objDictionary, i
Dim arrKeys, Key

Set objDictionary = CreateObject("scripting.dictionary")
objDictionary.add 1, "server1"
objDictionary.Add 2, "server2"
objDictionary.Add 3, "server3"
objDictionary.Add 4, "server4"

arrKeys = objDictionary.keys
wscript.echo "arrKeys is " & vartype(arrKeys)

For Each Key in arrKeys
wscript.echo "key " & key & " is a " & vartype(key)
Next

For i = 1 To objDictionary.count
WScript.Echo objDictionary.item (i)
Next

objDictionary.Add "5", "Server5"
WScript.Echo "The count after adding key ""5"" with ""server5""" & _
" to the dictionary is " & objDictionary.Count

For i = 1 To objDictionary.count
WScript.Echo objDictionary.item (i)
Next

WScript.Echo "The count after using the second for " _&
"... next loop Is " & objDictionary.Count

WScript.Echo "Key ""5"" is a " & typename(objdictionary.item("5"))
WScript.Echo "Key 6 is a " & typename(objdictionary.item(6))
 
The 5th addition to the dictionary is a string, not an integer. When the For...Next loop tries to read it, it cannot and it automatically adds an additional dictionary item incrementing the objDictionary.count by 1.

Yay me.
 
The fact is that the functionality of item property of dictionary object is not properly understood. The successes on keys 1,2,3,4 are illusionary.
[tt]
arrKeys = objDictionary.keys
For i = 1 To objDictionary.count
[red]'[/red]WScript.Echo objDictionary.item (i)
WScript.Echo objDictionary.item ([blue]arrKeys(i-1)[/blue])
Next
[/tt]
Or you can do as well with this.
[tt]
dim arrItems
arrItems=objDictionary.items
for i=0 to objDictionary.count-1
WScript.echo arrItems(i)
next
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top