Suppose I want to construct an association of associations, such as a list of people with attributes:
peopleFacts=<| alice-> <|age->29,shoeSize->7|>, bob-> <|age->27,sex->male|> |>
However, I want to grow and update this organically by adding facts as I learn them.
peopleFacts[["steve","hairColor"]] = "red";
peopleFacts[["bob","age"]] = "22";
peopleFacts[["steve","major"]] = "physics";
It's possible to accomplish this awkwardly by either (a) filling the database with blank entries or (b) laboriously checking at each level of association to see if an entry is blank before filling it in (except the last level, where AssociateTo
helps you). But I think there must be a more elegant way. Here is what I've tried.
This method breaks because it tosses out the second key:
In[]:= peopleFacts[["steve","hairColor"]] = "red";
peopleFacts
Out[]:= <|steve -> red, alice-> <|age->29,shoeSize->7|>, bob-> <|age->27,sex->male|> |>
This method drops existing data:
In[]:= peopleFacts
Out[]:= <| alice-> <|age->29,shoeSize->7|>, bob-> <|age->27,sex->male|> |>
In[]:= AssociateTo[peopleFacts, alice-> <|"sport"->"baseball"|>;
peopleFacts
Out[]:= <| alice-> <|sport->baseball|>, bob-> <|age->27,sex->male|> |>
This method just doesn't evaluate:
In[]:= AssociateTo[peopleFacts[["chris"]], "favoriteFood" -> "sushi"]
Out[]:= AssociateTo[peopleFacts[["chris"]], "favoriteFood" -> "sushi"]
EDIT: Here is a way-too-awkward method adapted from this answer by SuTron.
In[]:= peopleFacts
Out[]:= <| alice-> <|age->29,shoeSize->7|>, bob-> <|age->27,sex->male|> |>
In[]:= Module[{temp = peopleFacts["alice"]},
AssociateTo[temp, "sport"->"baseball"];
AssociateTo[peopleFacts, "alice" -> temp];
];
peopleFacts
Out[]:= <| alice-> <|age->29,shoeSize->7,sport->baseball|>, bob-> <|age->27,sex->male|> |>
It's not hard to imagine defining a custom update function like
NestedAssociateTo[peopleFacts,{"steve","haircolor","red"}]
that would handle this all for you, but I'd much rather have a nice native Mathematica solution that is optimized, and that I don't have to maintain or worry about.