Wolfram Research

Function Repository Resource:

AssociationMapAt

Source Notebook

Similar to MapAt but with improved behavior for nested expressions involving associations

Contributed by: Paco Jain (Wolfram Research)

ResourceFunction["AssociationMapAt"][f,assoc,atSpec]

applies f to the association assoc at the position(s) specified by atSpec.

Details and Options

AssociationMapAt is similar in usage to MapAt but has different behavior when used with associations.
For its third argument, AssociationMapAt takes a list consisting of any of the following: explicit integers, Span expressions, strings, Key expressions or All.
AssociationMapAt will not give messages if the position specified by atSpec does not exist, or is ragged, in assoc. Contrast ResourceFunction["AssociationMapAt"][f, <|"a"<||>, "b"<|"x" 1|>|>, {All, "x"}] with MapAt[f, <|"a"<||>, "b" <|"x"1|>|>, {All, "x"}].

Examples

Basic Examples

Apply a function to parts of a nested association:

In[1]:=
testAssoc = <|"chem1" -> <|"Density" -> 12, "Color" -> White|>, "chem2" -> <|"Color" -> Red|>|>;
ResourceFunction["AssociationMapAt"][f, testAssoc, {All, "Color"}]
Out[2]=

Apply a function to “ragged” parts of a nested association:

In[3]:=
ResourceFunction["AssociationMapAt"][f, testAssoc, {All, "Density"}]
Out[3]=

Apply a function to a part that doesn’t exist:

In[4]:=
ResourceFunction["AssociationMapAt"][f, testAssoc, {4}]
Out[4]=

Scope

The second argument of AssociationMapAt need not strictly be a nested association:

In[5]:=
ResourceFunction["AssociationMapAt"][f, g[<|a -> 1|>, b -> <||>], {All, Key[a]}]
Out[5]=
In[6]:=
ResourceFunction[
 "AssociationMapAt"][f, <|a -> g[x, y], b -> <||>|>, {Key[a], 1}]
Out[6]=

Properties and Relations

Contrast the behavior of MapAt and AssociationMapAt:

In[7]:=
 MapAt[f, <|"a" -> <||>, "b" -> <|"x" -> 1|>|>, {All, "x"}]
Out[7]=
In[8]:=
ResourceFunction[
 "AssociationMapAt"][f, <|"a" -> <||>, "b" -> <|"x" -> 1|>|>, {All, "x"}]
Out[8]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information