Dict (dictionary)
A dict is a dynamic associative list whose keys are texts. As in a real dictionary, you can use words as key and definitions as value, and retrieve a definition for a word.A dict is similar to an array, but keys are always texts, while array's key are integer numbers.
Examples of a dict declaration | dict
d d["program"] = "what we want to write faster" print d["program"] |
Displays: | > what we want to write faster |
Initializing a dict
The initializer is a set of couples "key : value" enclosed in parenthesis.
The prefix is always optional as the compiler can recognize a dict even if
it is a single element.
Example of a dict initialization: | dict
d d = ("a" : "premier", "b" = 2, etc... ) d = ("a": 1) |
The values stored may be any kind of objects. The key can be a variable and the value an expression.
The first example associate "b"
to the "a" key. The second example stores "bxxxx20" into the dict d, with the key "a". |
text
k = "a" text v = "b" dict d = (k : v) d.display() dict d = (k, v + "x".dup(4) + 20.toText()) d.display() |
Displays: | >
dict( a : b ) > dict( a : bxxxx20 ) |
An empty dict is created with this statement:
dict d = ()
Unlike arrays, it is filled by assignments:
d[k] = "b"
d["first"] = "element 1"
The content of a dict is erased by assigning nil or ():
d = nil
d = ()
Exercises |
1) Suppress the second element of this dict, and
display it: dict d = ("a": 1, "b": 2, "c": 3) Answer |