根据值对字典进行排序并提取相应的键

时间:2015-08-31 03:20:28

标签: ios swift

我在Swift中有一个带有键,值对的字典数据结构,我想根据值按降序对字典进行排序,然后得到对应于前3个值的前3个键。

示例:

排序前的

Dictionary<'A', 8>
Dictionary<'B', 23>
Dictionary<'C', 56>
Dictionary<'D', 3>
Dictionary<'E', 9>
Dictionary<'F', 20>

排序后:

 Dictionary<'C', 56>
 Dictionary<'B', 23>
 Dictionary<'F', 20>
 Dictionary<'E', 9>
 Dictionary<'A', 8>
 Dictionary<'D', 3>

所以我需要C,B和A

3 个答案:

答案 0 :(得分:3)

要获得与字典的排序值相关联的前三个键,(1)按其值排序数组,(2)从排序的数组中按顺序获取键,然后(3)拉出来自该阵列的前3个键:

let dict = ["A":8, "B":23, "C":56, "D":3, "E":9, "F":20]

// Sort the dictionary by its values
let sortedArray = sorted(dict, {$0.1 > $1.1})

// Get an array of the keys from the sorted array
let keys = sortedArray.map {return $0.0 }

// Get the first three keys
let firstThreeKeys = keys[0..<3]
println(firstThreeKeys)

答案 1 :(得分:2)

在Swift 2中,您可以这样做:

a if cond else b

答案 2 :(得分:0)

for (key,value) in (Array(arr).sorted {$0.1 < $1.1}) {
    println("\(key):\(value)")
}