2015-08-31 48 views
2

我有一个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

+1

你的意思是你想要C,B和* F *? –

+0

对不起,是的,我的意思是C,B和F,谢谢你指出这一点...并感谢大家的答案! –

+0

是否有任何答案适合您? –

回答

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

这只是问题的一半。 OP需要按顺序排列前三个键。 – NRitH

3

要获得前三与字典相关的键rted值,(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) 
2

在夫特2你可以这样做:

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

let sa = dict.sort({$0.1 > $1.1}).prefix(3).map { $0.0 } // ["C", "B", "F"] 
+0

非常酷!但是这返回的值不是密钥,即[56,23,20] –

+0

感谢您指出!答案已更新。与你的差别不大 – MirekE