typestar

Dictionaries in Visual Basic

Key-value stores with TryGetValue, the lookup that cannot throw.

Dim stock As New Dictionary(Of String, Integer) From {
    {"flour", 12}, {"sugar", 5}
}
stock("yeast") = 9
stock("sugar") += 3

If stock.ContainsKey("flour") Then Console.WriteLine("flour on hand")

Dim salt As Integer
If Not stock.TryGetValue("salt", salt) Then salt = 0
Console.WriteLine($"salt jars: {salt}")

For Each pair In stock
    Console.WriteLine($"{pair.Key,-8} {pair.Value,3}")
Next

How it works

  1. From {{...}} pairs keys with values at construction.
  2. Assigning to a missing key adds it; += updates in place.
  3. TryGetValue fills a variable and reports success as Boolean.
  4. For Each pair walks KeyValuePairs with .Key and .Value.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
388
Tokens
107
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 3 of 3 in Collections, step 6 of 29 in Language basics.

← Previous Next →

Dictionaries in other languages