Function Repository Resource:

MergeNested

Source Notebook

Merge a list of nested associations

Contributed by: Sjoerd Smit

ResourceFunction["MergeNested"][{assoc1,assoc2,},f]

merges a list of nested associations recursively.

ResourceFunction["MergeNested"][f]

represents an operator form of ResourceFunction["MergeNested"] that can be applied to an expression.

Details

ResourceFunction["MergeNested"] recurses downward until the lists to merge are no longer valid key-value expressions for Merge.
ResourceFunction["MergeNested"] works on the same data types as Merge: associations, rules and lists of rules.

Examples

Basic Examples (1) 

Merge two nested associations of the same depth. The returned association will have all of the keys of the original two:

In[1]:=
ResourceFunction[
 "MergeNested"][{<|a -> <|b -> 1, c -> 3|>|>, <|
   a -> <|b -> 2, d -> 4|>|>}, f]
Out[1]=

Scope (2) 

Use the operator form instead:

In[2]:=
ResourceFunction["MergeNested"][
  f]@{<|a -> <|b -> 1|>|>, <|a -> <|b -> 2, c -> 3|>|>}
Out[2]=

Merge different types of key-value data:

In[3]:=
ResourceFunction[
 "MergeNested"][{<|
   a -> <|c -> 1, b -> 10|>|>, {a -> {c -> 2, d -> 3}}, a -> c -> 4}, Identity]
Out[3]=

Applications (1) 

Merging with Last returns an association where the values of keys are taken from the rightmost association where that value is defined. This essentially mimics a hierarchical inheritance structure:

In[4]:=
ResourceFunction["MergeNested"][{
  <|a -> <|b -> 1, c -> 3|>, g -> <|h -> 10|>|>,
  <|a -> <|c -> 4, d -> 5|>|>
  }, Last
 ]
Out[4]=

Properties and Relations (2) 

Merging an empty list returns the empty association:

In[5]:=
ResourceFunction["MergeNested"][{}, f]
Out[5]=

For simple associations and other key-value data, MergeNested is identical to Merge:

In[6]:=
Merge[{<|a -> 1, b -> 2|>, <|a -> 5, b -> 10|>}, Total]
Out[6]=
In[7]:=
ResourceFunction[
 "MergeNested"][{<|a -> 1, b -> 2|>, <|a -> 5, b -> 10|>}, Total]
Out[7]=
In[8]:=
ResourceFunction["MergeNested"][{<|a -> x|>, a -> y, {b -> z}}, Identity] === Merge[{<|a -> x|>, a -> y, {b -> z}}, Identity]
Out[8]=

Possible Issues (1) 

When merging associations of different depths, the merging stops as soon as the depth of the shallowest association is reached:

In[9]:=
ResourceFunction[
 "MergeNested"][{<|a -> <|b -> 1, c -> 3|>|>, <|a -> 3|>}, f]
Out[9]=

Publisher

Sjoerd Smit

Version History

  • 1.0.0 – 08 April 2022

Related Resources

License Information