# Removing a nested list associated with a key and inserting into a new list

I'm trying to remove nested lists that are associated with a key

a = {{1, 2, 3, 4} -> 1, {5, 6, 7, 8} -> 1, {9, 10, 11, 12} -> 2, {13, 14, 15, 16} -> 2};


In order to create two separate lists where;

b contains the nested lists associated with the key 1, but without the key;

c contains the nested lists associated with the key 2, but without the key.

Would anybody be able to help?

Thanks!

You can use GroupBy:

{b, c} = GroupBy[a, Last, Keys] /@ {1, 2}


{{{1, 2, 3, 4}, {5, 6, 7, 8}},
{{9, 10, 11, 12}, {13, 14, 15, 16}}}

Alternatively, you can use Merge after reversing each element of a:

{b2, c2} = Values @ Merge[Identity] @ (Reverse /@ a) ;
{b2, c2} == {b, c}


True

You can also get the same result using Cases:

{b3, c3} = Cases[a, Rule[p_, #] :> p] & /@ {1, 2}
{b3, c3} == {b, c}


True

• Thank you for your reply. Would this work this same for a list that had 0 for its key? Eg: a={{1,2,3,4}->0, {5,6,7,8}->1} Commented Feb 13, 2020 at 21:05
• @Luke4737, if you mean something like ax = {{1, 2, 3, 4} -> 1, {5, 6, 7, 8} -> 1, {9, 10, 11, 12} -> 2, {13, 14, 15, 16} -> 2, {stuff, etc} -> 0} as input list, you can use {l0, l1, l2} = GroupBy[ax, Last, Keys] /@ {0, 1, 2} (or more generally, separatedlists = GroupBy[ax, Last, Keys] /@ ax[[All, -1]]) Similarly, for other methods.
– kglr
Commented Feb 13, 2020 at 21:18

With Query.

Query[GroupBy[Values -> Keys] /* KeySort /* Values]@a


or without

Values@KeySort@GroupBy[Values -> Keys]@a


Both give

{{{1, 2, 3, 4}, {5, 6, 7, 8}},
{{9, 10, 11, 12}, {13, 14, 15, 16}}}


KeySort ensures the key sets are order by their value.

Hope this helps.

a =
{{1, 2, 3, 4} -> 1,
{5, 6, 7, 8} -> 1,
{9, 10, 11, 12} -> 2,
{13, 14, 15, 16} -> 2};


Using GatherBy

Keys /@ GatherBy[a, Last]


{{{1, 2, 3, 4}, {5, 6, 7, 8}},
{{9, 10, 11, 12}, {13, 14, 15, 16}}}

Using SequenceSplit (new in 11.3)

SequenceSplit[a, x : {(_ -> y_), (_ -> y_) ..} :> First /@ x]


{{{1, 2, 3, 4}, {5, 6, 7, 8}},
{{9, 10, 11, 12}, {13, 14, 15, 16}}}

If a isn't sorted:

SequenceSplit[SortBy[Last] @ a, ...]