# Sort Associations by its Values (which are nested lists)

I have associations where the values are nested lists:

assoclist= <|KeyA -> {{a,b,2},{c,d,4},{e,f,3}},
KeyB -> {{a,b,1},{c,d,4},{e,f,6}}, KeyC -> {{a,b,2},{c,d,6},{e,f,9}}|>;


Now I need to sort the associations by the total sum of the third elements (here the numbers) in each list so that Key C comes first (total sum = 17), than Key B (11) and Key A (9).

How can I do this?

• SortBy[assoclist, -Total[#[[All, 3]]]&]? (Or use ReverseSortBy and get rid of the minus sign) – Sjoerd Smit Aug 30 '19 at 10:53
• @SjoerdSmit: I have tried this before but it did not work. It must have been a typing error or so. However now it works perfectly, thx! – M.A. Aug 30 '19 at 11:08

You may use ReverseSortBy with Total and Composition.

ReverseSortBy[Last@*Total]@assoclist


Hope this helps.

• Beautiful use of the Wolfram Language. The absence of specific list indices is very nice. It is also easily extended by changing Last or Total as needed. – Lee Aug 30 '19 at 22:19

E.g:

assoclist[[Reverse[Ordering[Total[assoclist[[All, All, 3]]]]]]]


With Transpose:

assoclist //
Map[Transpose] //
ReverseSortBy[Total@*Last] //
Map[Transpose]