Suppose I have a list of rules whose keys are not of identical structure (in my case, the keys are either lists of at least one symbol or symbols alone):
rules = {{a} -> 1, {b, c} -> 1, d -> 2, {e, f} -> 2, {g, g} -> 3, g -> 4};
The aim is to get all keys with matching values grouped together to end up with
newRules = {{a, b, c} -> 1, {d, e, f} -> 2, {g, g} -> 3, {g} -> 4};
I have what seems to me to be a hacky attempt to do this:
Reverse /@
Normal[
Merge[
Association /@ Reverse /@ rules, Flatten]
] == newRules
(* True *)
Are there any better ways to do this?
Flatten[#[[;; , 1]]] -> #[[1, 2]] & /@ GatherBy[rules, Last]
. $\endgroup$GroupBy[List @@@ rules, Last -> Most, Flatten] // GeneralUtilities`AssociationInvert
$\endgroup$Reverse[Normal[GroupBy[rules, Last -> First, Flatten]], 2]
$\endgroup$