按值排序字典 [英] Swift sort dictionary by value
问题描述
我有一个字典, [String:Double]
包含以下数据:
I have a dictionary, [String : Double]
with the following data:
Museum1 : 8785.8971799638
Museum2 : 34420.9643422388
Museum3 : 826.467789130732
Museum4 : 304120.342151219
我想用双重值排序字典。我做了一些研究,但所有的例子都被弃用了当前版本的Swift
I'd like to sort the dictionary by the double value. I did some research, but all of the examples are deprecated for the current version of Swift
我试过使用这个代码从 Swift中按值排列的字典:
I've tried using this code from Sort Dictionary by values in Swift:
for (k,v) in Array(self.museumsDic).sorted({$0.0 < $1.0}) {
println("\(k):\(v)")
}
但它不工作。如何用字母排序字典?
But it doesn't work. How can I sort the dictionary by its values?
推荐答案
目前还不清楚您的期望是什么。真的没有排序字典这样的东西。你的代码基本上是正确的,除了放错位置的括号。我试过这个:
It is not clear what your expectations are. There is really no such thing as a sorted dictionary. Your code is basically correct except for a misplaced parenthesis. I tried this:
let d = ["Museum1":8785.8971799638,
"Museum2":34420.9643422388,
"Museum3":826.467789130732,
"Museum4":304120.342151219]
for (k,v) in (Array(d).sorted {$0.1 < $1.1}) {
println("\(k):\(v)")
}
结果:
Museum3:826.467789130732
Museum1:8785.8971799638
Museum2:34420.9643422388
Museum4:304120.342151219
如果你认为这是错误的,你需要解释为什么。
If you think that's wrong, you need to explain why.
这篇关于按值排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!