Especially in tree-structured data, keys and values, being two sides of the same coin, frequently interchange roles. The ability to aggregate by value but not by key upsets the balance.
How to improve on this workaround query - here defined only in operator form?
keyGroupBy[f_][expr_] := expr // AssociationMap[First[#] -> # &] // GroupBy[First /* f] // Map[Values /* Association]
For example, given:
data = Range // AssociationMap[foo] (* <|1 -> foo, 2 -> foo, 3 -> foo, 4 -> foo, 5 -> foo|> *)
The desired output is:
data // keyGroupBy[PrimeQ] (* <|False -> <|1 -> foo, 4 -> foo|>, True -> <|2 -> foo, 3 -> foo, 5 -> foo|>|> *)
A fundamental constraint is that keys are transparent to functions accessing
Association supports only data with unique keys. For example,
GroupBy nested in
AssociationMap will drop all but the last key-value pair with a given key.