Skip to content

Quickly Add Items to a Dictionary

The Dictionary is a great class for managing a collection of items. A Dictionary gives you fast lookup of information which consists of two parts. The first part is a key that is a unique way to identify a value, which is the second part. These are each Variants so you can put any data type you want into the Dictionary.

You commonly use the Value method to add and get items from the Dictionary. For example, this adds “Red Sox” as the value for the key “TeamName”:

Dim teamDictionary As New Dictionary
teamDictionary.Value("TeamName") = "Red Sox"

Additional items are added the same way:

teamDictionary.Value("City") = "Boston"

This can get a bit tedious if you have lots of items to add. Instead you can make use of the Dictionary Constructor which takes a ParamArray of Pairs to populate it. A Pair is a class that has a Left value and a Right value. You could create a Pair like this:

Dim team As Pair = "TeamName":"Red Sox"

By using this Constructor, you can instead populate the Dictionary with one line like this:

Dim teamDictionary As New Dictionary("TeamName":"Red Sox", "City":"Boston")

I hope you find this tip useful. You can learn more about the Dictionary class here: