Wolfram Computation Meets Knowledge

The Wolfram Language:
Fast Introduction for Programmers

Show additional notes for:
All sections 
Get Started

Associations

Notes for Java programmers:

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

Notes for Python programmers:

Python dictionaries work similarly to associations in the Wolfram Language. Using an Association, programmers can associate keys to values with highly efficient lookup and updating, even with millions of elements, and they also preserve the order of element insertion, without needing specialized data structures like Python's OrderedDict.

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

In[1]:=1
<|"a" -> x, "b" -> y|>
Out[1]=1

(The keys in associations don't have to be strings, but often are.)

Applying an association to a key gives the corresponding value:

In[2]:=2
%["a"]
Out[2]=2

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

In[1]:=1
{#b, 1+#b} & [<|"a"->x, "b" -> y |>]
Out[1]=1

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

In[1]:=1
<|"a" -> x, "b" -> {5, 6}|>[["b", 1]]
Out[1]=1

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

In[1]:=1
TemplateApply["first `a`; second `b`; first `a`", <|"a" -> x, "b" -> y|>]
Out[1]=1

QUICK REFERENCE: Associations


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


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


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"|>?

© 2017 Wolfram. All rights reserved.