Function Repository Resource:

KeyMapIf

Source Notebook

Map a function conditionally over keys in an association

Contributed by: Seth J. Chandler

ResourceFunction["KeyMapIf"][f,test,assoc]

applies f to only those keys ki in assoc for which test[ki] gives True.

ResourceFunction["KeyMapIf"][f,test]

is the operator form of ResourceFunction["KeyMapIf"].

ResourceFunction["KeyMapIf"] uses the same programming constructs as the resource function MapIf.

Examples

Basic Examples (3) 

Map the function f over the keys of an Association, but only if the key is a string:

In[1]:=
ResourceFunction["KeyMapIf"][f, StringQ, Association["a" -> 4, 3 -> 5]]
Out[1]=

Turn any keys that are numeric in an Association into strings, using InputForm to show that it worked:

In[2]:=
ResourceFunction["KeyMapIf"][ToString, NumericQ, Association["a" -> 4, 3 -> 5]] // InputForm
Out[514]=

Use the operator form, using the resource function ShowQuotes to show that it worked:

In[515]:=
ResourceFunction["KeyMapIf"][ToString, NumericQ][
  Association["a" -> 4, 3 -> 5]] // ResourceFunction["ShowQuotes"]
Out[515]=

Compare the output from an EntityValue operation before KeyMapIf is used with the much nicer output after being adjusted by KeyMapIf:

In[516]:=
With[{output = EntityValue[
    SampledEntityClass[
     "DogBreed", {6, 9}], {EntityProperty["DogBreed", "Shedding"], "WeightMaleMean"}, "EntityPropertyAssociation"]}, Column@{Framed@Labeled[Dataset[output], "before"], Framed@Labeled[
     Dataset[Query[
        ResourceFunction["KeyMapIf"][CanonicalName, MatchQ[#, _Entity] &], ResourceFunction["KeyMapIf"][CanonicalName, MatchQ[#, _EntityProperty] &]][output]], "after"]}]
Out[516]=

As with the resource function MapIf, KeyMapIf does not itself support level specifications. KeyMapIf can operate at deeper levels of an Association, however, through the use of Query:

In[517]:=
Query[All, ResourceFunction["KeyMapIf"][f, StringQ]][{Association["a" -> 4, "b" -> 6], Association["a" -> 5, x -> 8]}]
Out[517]=

KeyMapIf can work on an Association of associations contained in a Dataset (or even more deeply):

In[518]:=
Query[ResourceFunction["KeyMapIf"][StringReverse, StringContainsQ[#, "n"] &], ResourceFunction["KeyMapIf"][f, StringQ]][
 Dataset[Association["1st" -> Association["a" -> 4, 5 -> 6], "2nd" -> Association["a" -> 5, 5 -> 8]]]]
Out[518]=

Publisher

Seth J. Chandler

Version History

  • 1.0.0 – 26 July 2019

Related Resources

License Information