How can I sort a TCL array based on the values of its keys?
INITIAL_ARRAY
-
Key -> Value
B 8
C 10
A 5
E 3
D 1
To get a sorted array based on a key, I use
set sorted_keys_array [lsort [array names INITIAL_ARRAY]]
to get out
Key -> Value
A 5
B 8
C 10
D 1
E 3
As wise as how to get a sorted tcl array based on key values like the output below?
Key -> Value
C 10
B 8
A 5
E 3
D 1
source to share
Since Tcl 8.6, you can do
lsort -stride 2 -integer [array get a]
which will create a flat list of key / value pairs sorted by value.
Before you lsort
got the option -stride
, you had to resort to building a list of lists from a flat list array get
and then sorting it using a parameter -index
for lsort
:
set x [list]
foreach {k v} [array get a] {
lappend x [list $k $v]
}
lsort -integer -index 1 $x
source to share
The previous methods for this did not work for me when I have an array:
[array get a] == D 1 E 3 A 5 B 8 C 10
I do the following and I get the error:
lsort -stride 2 -integer [array get a]
expected integer but got "D"
You also need to add an index:
lsort -integer -stride 2 -index 1 [array get a]
D 1 C 10 E 3 A 5 B 8
And then you can change direction:
lsort -decreasing -integer -stride 2 -index 1 [array get a]
C 10 B 8 A 5 E 3 D 1
Which then gives the correct answer
source to share