4
$\begingroup$

This question already has an answer here:

Suppose I have these two associations:

association1=<|
               "a" -> <|"b" -> <|"c" -> "txt1"|> |>,
               "d" -> <|"e" -> <|"f" -> "txt2"|> |>
             |>;

association2=<|
               "a" -> <|"b" -> <| "C" -> "TXT1"|> |>,
               "d" -> <|"e" -> <| "F" -> "TXT2"|> |>
             |>;

And I want to merge them. Notice that the keys at the first two levels are the same, so the merging needs to happen at the third level. The expected result is:

<|
  "a" -> <|"b" -> <|"c" -> "txt1", "C" -> "TXT1"|> |>,
  "d" -> <|"e" -> <|"f" -> "txt2", "F" -> "TXT2"|> |>
|>

Is there a elegant way of doing this? The best I have come up with is:

Merge[{association1, association2}, 
      Merge[#, Merge[#, Identity] &] &
     ] /. {x_String} :> x

A merge inside a merge inside a merge and then post process it with a replacement rule. This makes me think that there must be a better way to do this simple operation.

Notice that the depth of the associations is 4 not 3 like in the related

Update: There is a related question at How to organically merge nested associations? involving associations with Depth[peopleFacts] of 3. In my question the associations have a depth of 4, so I think this is not a duplicate.

$\endgroup$

marked as duplicate by Kuba, WReach, happy fish, Feyre, MarcoB Nov 7 '16 at 17:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ The OP in the related question expressly requested (in comments) that the solution must work to arbitrary depth. Kuba's MergeNested solution fulfills that requirement and produces the result you want. $\endgroup$ – WReach Nov 7 '16 at 15:56
  • $\begingroup$ In my case, I don't want it to work for an arbitrary depth (unless it is simpler than xavier response). I want the simplest possible way of merging associations with the structure shown. $\endgroup$ – Gustavo Delfino Nov 7 '16 at 16:28
4
$\begingroup$

With one Merge less, and using the operator form of Merge:

Merge[{association1, association2}, Merge[Association]]

(* <|
     "a" -> <|"b" -> <|"c" -> "txt1", "C" -> "TXT1"|>|>, 
     "d" -> <|"e" -> <|"f" -> "txt2", "F" -> "TXT2"|>|>
   |> *)
$\endgroup$
  • $\begingroup$ Ahh.. this looks much better. Thank you xavier. $\endgroup$ – Gustavo Delfino Nov 7 '16 at 15:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.