Any convenient ways to apply a function to Keys
that match a pattern in an Association
? Method should handle:
- Mixture of
String
,Symbol
and composite Keys - Preserve the input Association order
- Be efficient
Off the bat, KeyValuePattern
only matches a single instance per Association, so normalizing an Association into singleton Associations is not likely to satisfy (3)
Illustrating current gap in functionality rather than a path to solution (Dataset is not strictly necessary but helps abbreviate Queries)
ds = <|"b2" -> 2, "a1" -> 1, c3 -> 3|> // Dataset
Note c3
is a Symbol - Suppose the pattern is:
keyPattern = k_String /; StringMatchQ[k, "a*"]
This tentative query:
keyPatternQuery[patt_ -> f_][as_Association] :=
Query[{KeySelect[MatchQ[patt]] /* Query[All, f],
KeySelect[MatchQ[patt ] /* Not]} /* Apply[Join]][as];
Fails (2) or would require resorting by input keys, likely failing (3)
ds[keyPatternQuery[keyPattern -> f]] // Normal
<|"a1" -> f[1], "b2" -> 2, c3 -> 3|>