按值排序Tcl dict [英] Sort Tcl dict by value

查看:389
本文介绍了按值排序Tcl dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个优雅的方式来排序Tcl中的值。

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

假设我有一个以下dict:

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

我希望有一些类似于Python的sorted()的东西。

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

推荐答案

有,如果你有Tcl 8.6(这使用字典可以从列表中轻松转换):

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]

如果你仍然在8.5(可能; 8.6仍然在测试版),那么你需要使用几个步骤:

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]

如果你有这个选项, -stride 选项更容易使用。

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

这篇关于按值排序Tcl dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆