TCL 如何按值对嵌套字典进行排序

TCL how to sort a nested dictionary by value

输入是一个名为 b

的字典
puts $b
h1 {tP 20} h2 {tP 30} h3 {tP 40} h4 {tP 50}

Objective - 按 tP 值对字典排序。

我现在的功能是

proc sortValue {dict args} {
    set l {}
    dict for {k v} $dict {
        lappend l [list $k $v]
    }
    return [concat {*}[lsort -real -decreasing -index 1 {*}$args $l]]
}

如何修改它以进入另一个级别的字典?

预期输出

h4 {tP 50} h3 {tP 40} h2 {tP 30} h1 {tP 20}

将 dict 视为具有偶数个元素的列表(它是)

lsort -integer -decreasing -stride 2 -index {end end} $b
h4 {tP 50} h3 {tP 40} h2 {tP 30} h1 {tP 20}

第一个 "end" 是访问步幅的最后一个元素,第二个 "end" 是访问该索引的最后一个元素。


您可以在 8.5 中执行此操作

set temp [list]
set sorted [dict create]

dict for {key value} $b {
    lappend temp [list $key $value]
}
foreach pair [lsort -integer -decreasing -index {end end} $temp] {
    dict set sorted {*}$pair
}

刚刚看到你编辑的评论:是的,当然会改变。这是一个 Schwartzian 变换:

% set b {h1 {tP 20 lp 1} h2 {tP 30 lp 2} h3 {tP 40 lp 3} h4 {tP 50 lp 4} }
h1 {tP 20 lp 1} h2 {tP 30 lp 2} h3 {tP 40 lp 3} h4 {tP 50 lp 4}
% set temp [list]
% dict for {key subdict} $b {lappend temp [list [dict get $subdict tP] $key $subdict]}
% set sorted [dict create]
% foreach tuple [lsort -int -decr -index 0 $temp] {dict set sorted {*}[lrange $tuple 1 end]}
% set sorted
h4 {tP 50 lp 4} h3 {tP 40 lp 3} h2 {tP 30 lp 2} h1 {tP 20 lp 1}