Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Tcl dict by value

I was wondering if there is an elegant way of sorting dict by value in Tcl.

Suppose I have a following dict:

set d1 [dict create k1 10 k2 89 k3 1 k4 15 k5 20]
# Results in dict of form
# k1 => 10
# k2 => 89
# k3 => 1
# k4 => 15
# k5 => 20

Now I want to sort this dictionary so that I have:

# k3 => 1
# k1 => 10
# k4 => 15
# k5 => 20
# k2 => 89

I was hoping there is something similar to Python's sorted().

like image 583
Malcolm32 Avatar asked Dec 12 '22 13:12

Malcolm32


1 Answers

There is, if you have Tcl 8.6 (this uses the fact that dictionaries can be converted cheaply to and from lists):

set sorted [lsort -integer -stride 2 -index 1 $d1]

If you're still on 8.5 (likely; 8.6 is still in beta) then you need to use several steps:

proc sortDictByValue {dict args} {
    set lst {}
    dict for {k v} $dict {lappend lst [list $k $v]}
    return [concat {*}[lsort -index 1 {*}$args $lst]]
}
set sorted [sortDictByValue $d1]

The -stride option is easier to use, if you've got it.

like image 61
Donal Fellows Avatar answered Dec 22 '22 21:12

Donal Fellows