Skip to main content

gathering - How to organically merge nested associations?



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.



Answer



Initial data:


peopleFacts = <|

alice -> <|age -> 29, shoeSize -> 7|>,
bob -> <|age -> 27, sex -> male, hair -> <|Color -> RGBColor[1, 0, 0]|>
|>
|>;



Here is a version of RecurAssocMerge reduced to a single definition.


MergeNested = If[MatchQ[#, {__Association}], Merge[#, #0], Last[#]] &

MergeNested @ {peopleFacts, <|bob -> <|hair -> <|length -> 120|>|>|>}



 <|
alice -> <|
age -> 29,
shoeSize -> 7|>,
bob -> <|
age -> 27,
sex -> male,
hair -> <|Color -> RGBColor[1, 0, 0], length -> 120|>

|>
|>



Special case of 2-level deep association


Merge[{
peopleFacts,
<|bob -> <|hairColor -> 1|>|>
},
Association

]

"Tidy" approach to write NestedMerge:


RecurAssocMerge[a : {__Association}] := Merge[a, RecurAssocMerge];
RecurAssocMerge[a_] := Last[a];



  • adding key to deep level association:


    RecurAssocMerge[

    {peopleFacts, <|bob -> <|hair -> <|length -> 120|>|>|>}
    ]


     <|alice -> <|age -> 29, shoeSize -> 7|>, 
    bob -> <|age -> 27, sex -> male, hair -> <|
    Color -> RGBColor[1, 0, 0], length -> 120 |>
    |>
    |>




  • entirely new tree


    RecurAssocMerge[
    {peopleFacts, <|kuba -> <|hair -> <|length -> 120|>|>|>}
    ]


     <|
    alice -> <|age -> 29, shoeSize -> 7|>,

    bob -> <|age -> 27, sex -> male, hair -> <|Color -> RGBColor[1, 0, 0]|>
    |>,
    kuba -> <|hair -> <|length -> 120|>|>
    |>





Section added by Jess Riedel:


Specialize to single new entry



RecurAssocMerge defined above is a general method for merging nested Associations. We can define an abbreviation for the special case when we are adding only a single new entry.


RecurAssocMerge[ini_Association, path_List, value_] := RecurAssocMerge[{
ini, Fold[<|#2 -> #|> &, value, Reverse@path]
}]

Then we can just do


RecurAssocMerge[peopleFacts, {bob, hair, length}, 120]


 <|alice -> <|age -> 29, shoeSize -> 7|>, 

bob -> <|age -> 27, sex -> male, hair -> <|
Color -> RGBColor[1, 0, 0], length -> 120 |>
|>
|>

Notes


If you want to modify peopleFacts the peopleFacts = Merge... is needed of course.


Comments