Jump to content

Visual Basic/Dictionaries

From Wikibooks, open books for an open world

Dictionary class provides some functions beyond those provided by Collection class. A dictionary is a list of key, value pairs. Unlike Collection, Dictionary class is only available via Microsoft Scripting Runtime, a reference to which needs to be added to your project in order to use the class.

Creating a dictionary:

  Set Dict = New Dictionary
  Set Dict = CreateObject("Scripting.Dictionary") 'An alternative

Adding a key and an item to a dictionary:

  Dict.Add "Key1", "Value1"
  Dict.Add "Key2", "Value2"
  Dict.Add Key:="Key3", Item:="Value3"

Accessing an item by key:

  Value3 = MyDict.Item("Key3")

Accessing an item by index:

  Index = 2
  Counter = 1
  For Each Key In Dict.Keys
    If Counter = Index Then
      FoundKey = Key
      FoundValue = Dict.Item(Key)
      Exit For
    End If
    Counter = Counter + 1
  Next

Iterating through the keys:

  For Each Key In Dict.Keys
    Value = Dict.Item(Key)
  Next

Iterating through the values:

  For Each Value In Dict.Items
    '...
  Next

Removing an item:

  Dict.Remove "Key3"

Removing all items or emptying:

  Dict.RemoveAll

Size or number of elements:

  Dict.Count

Testing for emptiness:

  If Dict.Count = 0 Then
    '...
  End If

Changing the key of an item:

  Dict.Key("Key1") = "Key1a"

Changing the value of an item:

  Dict.Item("Key2") = "Value2a"

Testing for presence of a key:

  If Dict.Exists("Key2") Then
    '..
  End If

Using dictionary as a set:

Associate the dummy value 1 with each element of the set.
When adding an item, test for existence.
  Set DictSet = New Dictionary
  DictSet.Add "Item1", 1
  'DictSet.Add "Item1", 1 -- error: the item is already there
  If Not DictSet.Exists("Item1") Then
    DictSet.Add "Item1", 1
  End If
  DictSet.Remove "Item1"