Wolfram: Association. Sort

By Xah Lee. Date: . Last updated: .

Sort by Keys, via Comparison Function

KeySort[ asso ]

sort by key, using builtin ordering.

KeySort[ Association[ 5 -> a, 3 -> c, 4 -> b] ]
(* <|3 -> c, 4 -> b, 5 -> a|> *)
KeySort[ asso, p ]

sort using a comparison function p.

p have the same spec as the comparison function in Sort

(* sort by asso keys, via the their sum *)
KeySort[
Association[{9, 9, 2} -> b, {2, 3} -> a, {2, 9} -> c],
Function[{x,y}, Total @ x < Total @ y ]
]
(* <|{2, 3} -> a, {2, 9} -> c, {9, 9, 2} -> 4|> *)

Sort by Keys, via Order Ranking Function

KeySortBy[ asso, f ]
  • Sort keys by an order-ranking function f.
  • The function is feed the key. The return value is used as order rank.
KeySortBy[
Association[ 5 -> a, 3 -> c, 4 -> b],
Identity
]
(* <|3 -> c, 4 -> b, 5 -> a|> *)

Sort by Values

to sort association by its values, you can use sort functions that work on list.

Sort Association by Values via Standard Order

(* sort asso by value *)
Sort[ Association[ a -> 5, c -> 3, b -> 4] ]
(* <|c -> 3, b -> 4, a -> 5|> *)

Sort Association by Values via Comparison Function

(* sort asso by value, by suming it *)
Sort[
Association[b -> {9, 3}, c -> {1, 0}, a -> {2, 1}],
 Function[{a,b}, Total[ a ] < Total[ b ] ]
]
(* <|c -> {1, 0}, a -> {2, 1}, b -> {9, 3}|> *)

Sort Association by Values via a Order Ranking Function

(* sort asso by value, by string length *)
SortBy[
Association[ 5 -> "bird", 3 -> "dog", 4 -> "cat"],
StringLength
]
(* <|3 -> dog, 4 -> cat, 5 -> bird|> *)

Reverse Association by Values

Reverse[ Association[ 5 -> a, 3 -> c, 4 -> b] ]
(* <|4 -> b, 3 -> c, 5 -> a|> *)

Wolfram. Sort

Wolfram. Association (Key Value List)