D has built-in associative arrays also known as hash maps.
An associative array with a key type of string
and a value type
of int
is declared as follows:
int[string] arr;
The value can be accessed by its key and thus be set:
arr["key1"] = 10;
To test whether a key is located in the associative array, the
in
expression can be used:
if ("key1" in arr)
writeln("Yes");
The in
expression returns a pointer to the value if it
can be found or a null
pointer otherwise. Thus existence check
and writes can be conveniently combined:
if (auto val = "key1" in arr)
*val = 20;
Access to a key which doesn't exist yields an RangeError
that immediately aborts the application. For a safe access
with a default value, get(key, defaultValue)
can be used.
AA's have the .length
property like arrays and provide
a .remove(val)
member to remove entries by their key.
It is left as an exercise to the reader to explore
the special .byKey
and .byValue
ranges.