VBScript dictionary exists Method always returns True

What am I doing wrong? Of my tests, objDic.exists NEVER gives False!

dim objDic set objDic = createobject("scripting.dictionary") objDic.add "test","I have not been deleted" wscript.echo objDic.item("test") 'Displays -- I have not been deleted objDic.remove "test" wscript.echo """" & objDic.item("test") & """" 'Displays -- "" if objDic.exists("test") then wscript.echo """" & objDic.item("test") & """" 'Displays -- "" 
+7
source share
4 answers

As far as I can tell, the Object Dictionary key is created simply by referencing it, as if it existed.

 wscript.echo objDic.Item("test") 'Creates the key whether it exists or not wscript.echo objDic.Exists("test") 'Will now return true 

Here is another code you can try to prove / test my theory. I usually use MsgBox instead of WScript.Echo, as you will see in my code.

 dim objDic, brk brk = vbcrlf & vbcrlf set objDic = createobject("scripting.dictionary") objDic.add "test","I have not been deleted" wscript.echo "objDic.Exists(""test""): " & brk & objDic.item("test") WScript.Echo "Now going to Remove the key named: test" objDic.remove "test" MsgBox "objDic.Exists(""test""): " & brk & objDic.Exists("test") 'Returns False wscript.echo "objDic.item(""test""): " & brk & objDic.item("test") 'Shows Blank, Creates the key again with a blank value wscript.echo "objDic.item(""NeverAdded""): " & brk & objDic.item("NeverAdded") 'Also shows blank, does not return an error MsgBox "objDic.Exists(""test""): " & brk & objDic.Exists("test") 'Returns True 
+12
source

Here was the same problem ...
My code has a dynamic array of dictionaries.
Some of the entries have the "HIGH" key, and some do not.
Testing for a key for each record always returned correctly:

 for each dictionary_entry in dictionary_array if dictionary_entry.Exists("HIGH") then msgbox("Hey, I have a HIGH key, and its value is " + dictionary_entry("HIGH)) next 

The debugger created a "HIGH" key for each dictionary if I looked at a variable.
To remove code that works correctly, you must remove both dictionary_entry and dictionary_array .

+1
source

Remove any scanned variables from the IDE that have anything to do with your dictionary. This is repeatable. You can invoke / fix the behavior this way (Outlook 2010 VBA IDE). It seems that the observer effect I suppose.,.

-M

0
source

The accepted answer did not answer my question. I imagine others, so I submit my solution, as this thread is the first result in google.

The key will be created by default if it does not exist. Dictionaries are designed to add entries if they do not exist, so true will always be returned below.

 If objDic.exists("test") then 

Since the key is created when you check for its existence, the value is undefined. Below it will be checked if the Key associated with it does not matter. Of course, this will not work with your dictionary if you have empty values.

 If objDic.item("test") <> "" then 
-2
source

All Articles