Im trying to Sort Rule-s according to Key-s (or names) but the normal Sort routine places String-s above Symbol-s. My goal is to have them Sort equally by names.
Here is the normal Sort routine. Notice that it places String names above Symbol-s.
ClearSystemCache[];
ClearAll["Global`*"];
names = {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, e -> 6, h -> 8,
"b" -> 2};
Sort[names]
(* Out: {"a" -> 1, "b" -> 2, "e" -> 6, "f" -> 6, c -> 3, d -> 4, g -> 7,
h -> 8} *)
Here are my two attempts at deriving a Sort function. Not good. No sorting occurs. Please help.
ClearSystemCache[];
ClearAll["Global`*"];
names = {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, "e" -> 6, h -> 8,
"b" -> 2};
Sort[names, ToString[#1] < ToString[#2] &]
(* Out: {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, "e" -> 6, h -> 8,
"b" -> 2} *)
p[ToString[_x], ToString[_y]] /; x > y := -1;
p[ToString[_x], ToString[_y]] /; StringMatchQ[x, y] := 0;
p[ToString[_x], ToString[_y]] /; x < y := 1;
Sort[names, p]
(* Out: {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, "e" -> 6, h -> 8,
"b" -> 2} *)
SortByfunction – mikado Nov 27 '22 at 08:51SortBy[names, ToExpression@Keys@# &]? – Syed Nov 27 '22 at 09:12SortBy[names, ToString]thank you. :) – Jules Manson Nov 27 '22 at 09:13SortBy[names, ToString]but thank you. – Jules Manson Nov 27 '22 at 09:14"d"<"h" // TrueQdoes not evaluate it toTrue, it's not possible to compare strings with<as can be checked in the Details section of Less. If you want to useSortyou can use for exampleSort[names, Order @@ ToString /@ {#1, #2} &]– userrandrand Nov 27 '22 at 09:56