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

Popular posts from this blog

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...

mathematical optimization - Minimizing using indices, error: Part::pkspec1: The expression cannot be used as a part specification

I want to use Minimize where the variables to minimize are indices pointing into an array. Here a MWE that hopefully shows what my problem is. vars = u@# & /@ Range[3]; cons = Flatten@ { Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; Minimize[{Total@((vec1[[#]] - vec2[[u[#]]])^2 & /@ Range[1, 3]), cons}, vars, Integers] The error I get: Part::pkspec1: The expression u[1] cannot be used as a part specification. >> Answer Ok, it seems that one can get around Mathematica trying to evaluate vec2[[u[1]]] too early by using the function Indexed[vec2,u[1]] . The working MWE would then look like the following: vars = u@# & /@ Range[3]; cons = Flatten@{ Table[(u[j] != #) & /@ vars[[j + 1 ;; -1]], {j, 1, 3 - 1}], 1 vec1 = {1, 2, 3}; vec2 = {1, 2, 3}; NMinimize[ {Total@((vec1[[#]] - Indexed[vec2, u[#]])^2 & /@ R...

How to remap graph properties?

Graph objects support both custom properties, which do not have special meanings, and standard properties, which may be used by some functions. When importing from formats such as GraphML, we usually get a result with custom properties. What is the simplest way to remap one property to another, e.g. to remap a custom property to a standard one so it can be used with various functions? Example: Let's get Zachary's karate club network with edge weights and vertex names from here: http://nexus.igraph.org/api/dataset_info?id=1&format=html g = Import[ "http://nexus.igraph.org/api/dataset?id=1&format=GraphML", {"ZIP", "karate.GraphML"}] I can remap "name" to VertexLabels and "weights" to EdgeWeight like this: sp[prop_][g_] := SetProperty[g, prop] g2 = g // sp[EdgeWeight -> (PropertyValue[{g, #}, "weight"] & /@ EdgeList[g])] // sp[VertexLabels -> (# -> PropertyValue[{g, #}, "name"]...