Dictionaries

A Dict is an associative dictionary which relates keys and values - the keys may be of any type. Dictionaries may be created in two ways. First, the new Dict() method may be used to create a dictionary with a given maximum size:

    d = new Dict(32) // Create a dictionary to hold 32 key/value pairs

Additionally, dictionaries can be created by using triple angle brackets, thus:

    d = <<< "red", [1.,0.,0.], "green", [0.,1.,0.], "blue", [0.,0.,1.]>>>

An even number of items must be specified between the triple angle brackets. The first of each pair is the key, and the second is the value associated with that key. Note that elements of a dictionary created with triple angle brackets may be replaced, but the dictionary may not grow beyond the number of pairs specified between the brackets. The reshape() method may be used to create a copy of a Dict which can hold a different number of items:

    // The dictionary from the previous example can hold 3 key/value pairs
    d.sizeof()
3

    // We need to store up to 10 pairs, so resize it
    d = d.reshape(10)
    d.sizeof()
10

    // It still only holds 3 key/value pairs
    d.length()
3

Dictionary insert, delete, and lookup

Dictionaries use the same bracket syntax as arrays to access and assign elements; however, dictionaries have only one "dimension". To insert a key/value pair into a dictionary, simply execute an array-like assignment:

    d["cyan"] = [0.,1.,1.]
    d.length()
4

The index expression is the key, and the right-hand side of the assignment is the value. Looking up a value in a dictionary is equally simple:

    "Red = ", d["red"]
Red = 1. 0. 0.

If the value is not found, the expression will evaluate to nil:

    "Purple = ", d["purple"]
Purple = nil

To delete an item from a dictionary, simply assign nil to the particular key:

    d.length()
4

    d["cyan"] = nil
    d.length()
3

Dictionaries have O(log(N)) complexity of insertions, lookups, and deletions. Additionally, although keys may be of any type, String and WideString keys are treated specially: the actual contents of the String or WideString is used as the key. Other Array-valued keys simply use the Array ID as the index for the dictionary. Finally, if the key stored in the dictionary or the key used for value lookup is a numeric value, the stored key and the lookup key are promoted to a compatible type according to the rules given in the Expressions chapter:

    d[1] = "two"
    d[1.0]
two

Back to Arrays, Lists, and Strings

Continue to Classes

Return to Introduction