Wolfram Language Fast Introduction for Programmers
Get Started »

Associations

Wolfram Language Associations are similar to Java's Map or HashMap, but with more readable syntax and much more flexible usage.

Wolfram Language Associations are similar to Python dictionaries.

Associations associate keys and values:
( is typed using ->)

In[1]:=
X
Out[1]=

(The keys in associations dont have to be strings, but often are.)

Applying an association to a key gives the corresponding value:

In[2]:=
X
Out[2]=

In a pure function, #key picks out the value corresponding to "key" in an association:

In[1]:=
X
Out[1]=

You can mix associations and lists, and pick out parts using [[ ... ]]:

In[1]:=
X
Out[1]=

String templates work with associations (as do XML and notebook templates):

In[1]:=
X
Out[1]=

This is similar to templating with dictionaries using the string package in Python.

QUICK REFERENCE: Associations »

Check Your Understanding

In the association <|"names" {"john", "ann"}, "numbers" {2, 3}|>, which of the following does NOT give the "names" element?

<|"names" {"john", "ann"}, "numbers" {2, 3}|>[["names"]]

Incorrect. This is one of the ways to get the names.

<|"names" {"john", "ann"}, "numbers" {2, 3}|>["names"]

Incorrect. This is one of the ways to get the names.

<|"names" {"john", "ann"}, "numbers" {2, 3}|>[1]

Correct. 1 is used as the key, not as the part, and so returns Missing[KeyAbsent, 1].

#names &[<|"names" {"john", "ann"}, "numbers" {2, 3}|>]

Incorrect. This is one of the ways to get the names.

Which of these extracts the age of the cat in the association
x=<|"cat" <|"vet" "Eve", "age" 5|>, "dog" <|"vet" "Abe", "age" 4|>|>?

x[["cat", "age"]]

Correct.

x["extract", "age"]

Incorrect. The string "extract" doesn't do anything.

x[["age", "cat"]]

Incorrect. The keys in the association are in the other order.

Which of the following applies a template to make a string with appetizer and dessert from the association
meal=<|"appetizer" "nachos", "salad" "spinach", "dessert" "chocolate"|>?

TemplateApply["The appetizer is `appetizer` and the dessert is `dessert`.", meal]

Correct.

TemplateApply["The appetizer is `` and the dessert is ``.", meal]

Incorrect. When applying a template to an association, the slots need to be labeled with the keys in the association.

TemplateApply["The appetizer is 'appetizer' and the dessert is 'dessert'.", meal]

Incorrect. The slots are indicated by `, not '.