Associations
Prerequisites: Rules and replacement
An association is a key-value map — like a dictionary in Python or
an object in JSON. It's written with <| and |>.
stock = <|"apple" -> 3, "banana" -> 5|>;
stock["apple"]
stock["cherry"]
Lookup[stock, "cherry", 0]
Keys[stock]
Values[stock]
3
Missing[KeyAbsent, cherry]
0
{apple, banana}
{3, 5}
- A missing key gives a
Missing[...]object, not an error. Lookup[assoc, key, default]supplies a default.- Keys keep the order you inserted them.
Changing an association
stock["cherry"] = 7;
stock
KeyDrop[stock, "banana"]
stock["apple"] += 1;
stock
<|apple -> 3, banana -> 5, cherry -> 7|>
<|apple -> 3, cherry -> 7|>
<|apple -> 4, banana -> 5, cherry -> 7|>
KeyDrop returns a new association; assigning to stock[key] changes
the variable.
Functions that work on values
prices = <|"apple" -> 3, "banana" -> 5, "cherry" -> 7|>;
2 # & /@ prices
Total[prices]
Select[prices, # > 4 &]
KeySort[<|"b" -> 2, "a" -> 1|>]
KeyValueMap[#1 <> ": " <> ToString[#2] &, prices]
<|apple -> 6, banana -> 10, cherry -> 14|>
15
<|banana -> 5, cherry -> 7|>
<|a -> 1, b -> 2|>
{apple: 3, banana: 5, cherry: 7}
Map, Select, Total, and many other functions treat an association
like a list of its values — while keeping the keys.
Building associations from data
Counts[{"a", "b", "a", "c", "a"}]
GroupBy[Range[10], Mod[#, 3] &]
AssociationThread[{"x", "y"}, {1, 2}]
Merge[{<|"a" -> 1|>, <|"a" -> 2, "b" -> 3|>}, Total]
<|a -> 3, b -> 1, c -> 1|>
<|1 -> {1, 4, 7, 10}, 2 -> {2, 5, 8}, 0 -> {3, 6, 9}|>
<|x -> 1, y -> 2|>
<|a -> 3, b -> 3|>
Lists of records
A list of associations is a natural way to hold a table:
people = {
<|"name" -> "Ada", "age" -> 36|>,
<|"name" -> "Alan", "age" -> 41|>,
<|"name" -> "Grace", "age" -> 45|>};
#name & /@ people
Select[people, #age > 40 &][[All, "name"]]
Mean[#age & /@ people]
{Ada, Alan, Grace}
{Alan, Grace}
122/3
- In a pure function,
#nameis shorthand for#["name"]. [[All, "name"]]takes the"name"of every record.Dataset(next lesson) builds on exactly this structure.
Practice
Count how many times each letter appears in "mississippi" and show the
most common one.
Show solution
c = Counts[Characters["mississippi"]]
Keys[Select[c, # == Max[c] &]]
<|m -> 1, i -> 4, s -> 4, p -> 2|>
{i, s}
i and s tie at 4, so both are returned. (TakeLargest[c, 1] would
return just one of them.)