Joining all the keys of a list of rules that point to matching values

 Joining all the keys of a list of rules that point to matching values

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?

3 Answers

Let’s block ads! (Why?)

Recent Questions – Mathematica Stack Exchange