Maps in Wolfram Language

In Wolfram Language, the equivalent of maps are called associations. They are the built-in associative data type, sometimes called hashes or dicts in other languages.

(* To create an empty association, use <| |> *)
m = <||>;

(* Set key/value pairs using typical name[key] = val syntax *)
m["k1"] = 7;
m["k2"] = 13;

(* Printing an association will show all of its key/value pairs *)
Print["association: ", m]

(* Get a value for a key with name[key] *)
v1 = m["k1"];
Print["v1: ", v1]

(* If the key doesn't exist, Missing["KeyAbsent", key] is returned *)
v3 = m["k3"];
Print["v3: ", v3]

(* The Length function returns the number of key/value pairs *)
Print["length: ", Length[m]]

(* To remove a key/value pair from an association, use KeyDrop *)
m = KeyDrop[m, "k2"];
Print["association: ", m]

(* To remove all key/value pairs from an association, reassign it to an empty one *)
m = <||>;
Print["association: ", m]

(* KeyExistsQ checks if a key is present in the association *)
prs = KeyExistsQ[m, "k2"];
Print["prs: ", prs]

(* You can also declare and initialize a new association in the same line *)
n = <|"foo" -> 1, "bar" -> 2|>;
Print["association: ", n]

(* The Association function can be used to create associations *)
n2 = Association["foo" -> 1, "bar" -> 2];
Print["n == n2: ", n === n2]

Note that associations appear in the form <|key -> value, key -> value|> when printed.

When you run this code, you should see output similar to:

association: <|"k1" -> 7, "k2" -> 13|>
v1: 7
v3: Missing["KeyAbsent", "k3"]
length: 2
association: <|"k1" -> 7|>
association: <||>
prs: False
association: <|"foo" -> 1, "bar" -> 2|>
n == n2: True

Wolfram Language’s associations provide similar functionality to maps in other languages, with some differences in syntax and behavior. The Association function and related operations offer powerful tools for working with key-value data structures.