按键排序字典

我想用 Swift 对一本字典进行分类。我有一本这样的字典:

"A" => Array[]
"Z" => Array[]
"D" => Array[]

等等,我希望它像

"A" => Array[]
"D" => Array[]
"Z" => Array[]

等等。

我已经尝试了很多解决方案,但没有人为我工作。我使用的是 XCode6 Beta 5,在它上面有些给出了编译器错误,有些解决方案给出了异常。所以任何人谁可以张贴工作副本的字典排序。

170907 次浏览
let dictionary = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]


let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]

编辑:

上面代码中的排序数组只包含键,而值必须从原始字典中检索。但是,'Dictionary'也是(键,值)对的 'CollectionType',我们可以使用全局 'sorted'函数来获得包含键和值的排序数组,如下所示:

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]

编辑2: 目前更喜欢每月更新一次的 Swift 语法

let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]

不推荐使用全局 sorted

如果希望按照键排序顺序对键和值进行迭代,则此表单非常简洁

let d = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]

迅捷1,2:

for (k,v) in Array(d).sorted({$0.0 < $1.0}) {
println("\(k):\(v)")
}

Swift 3 + :

for (k,v) in Array(d).sorted(by: {$0.0 < $1.0}) {
println("\(k):\(v)")
}

说明一下,你不能对字典进行排序,但是你可以输出一个可以排序的数组。

Swift 2.0

最新版本的 Ivica M 的回答:

let wordDict = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]


let sortedDict = wordDict.sort { $0.0 < $1.0 }
print("\(sortedDict)") //

Swift 3

wordDict.sorted(by: { $0.0 < $1.0 })

对于 Swift 3来说,下面的方法对我很有效,而 Swift 2的语法却不起作用:

// menu is a dictionary in this example


var menu = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]


let sortedDict = menu.sorted(by: <)


// without "by:" it does not work in Swift 3

在 iOS9和 xcode 7.3中“排序”,迅捷2.2是不可能的,将“排序”改为“排序”,像这样:

let dictionary = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]
let sortedKeysAndValues = Array(dictionary).sort({ $0.0 < $1.0 })
print(sortedKeysAndValues)


//sortedKeysAndValues = ["desert": 2.99, "main course": 10.99, "salad": 5.99]

对于 Swift 3,下面的排序将按键返回排序后的字典:

let unsortedDictionary = ["4": "four", "2": "two", "1": "one", "3": "three"]


let sortedDictionary = unsortedDictionary.sorted(by: { $0.0.key < $0.1.key })


print(sortedDictionary)
// ["1": "one", "2": "two", "3": "three", "4": "four"]

我尝试了以上所有的方法,简而言之,你所需要的就是

let sorted = dictionary.sorted { $0.key < $1.key }
let keysArraySorted = Array(sorted.map({ $0.key }))
let valuesArraySorted = Array(sorted.map({ $0.value }))

对于 Swift 4,以下方法对我很有效:

let dicNumArray = ["q":[1,2,3,4,5],"a":[2,3,4,5,5],"s":[123,123,132,43,4],"t":[00,88,66,542,321]]


let sortedDic = dicNumArray.sorted { (aDic, bDic) -> Bool in
return aDic.key < bDic.key
}

在迅捷4中,你可以写得更聪明:

let d = [ 1 : "hello", 2 : "bye", -1 : "foo" ]
d = [Int : String](uniqueKeysWithValues: d.sorted{ $0.key < $1.key })

Swift 3被排序(按: <)

let dictionary = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]


let sortedKeys = Array(dictionary.keys).sorted(by:<) // ["A", "D", "Z"]

这是对字典本身进行分类的一个优雅的替代方案:

截至斯威夫特4 & 5

let sortedKeys = myDict.keys.sorted()


for key in sortedKeys {
// Ordered iteration over the dictionary
let val = myDict[key]
}

Swift 5中,为了按 KEYS 对 Dictionary 进行排序

let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.0 < $1.0 })

为了按价值对字典进行排序

let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.1 < $1.1 })

Swift 5

输入要按字母顺序按键排序的字典。

// Sort inputted dictionary with keys alphabetically.
func sortWithKeys(_ dict: [String: Any]) -> [String: Any] {
let sorted = dict.sorted(by: { $0.key < $1.key })
var newDict: [String: Any] = [:]
for sortedDict in sorted {
newDict[sortedDict.key] = sortedDict.value
}
return newDict
}

排序(按: { $0。匙 < $1。{ key }) 通过它自己返回 Tuple(value,value)而不是 字典[ value: value ]。因此,for 循环解析元组以作为字典返回。这样,你放进一本字典,就能拿回一本字典。

Swift 4 & 5

对于字符串键排序:

dictionary.keys.sorted(by: {$0.localizedStandardCompare($1) == .orderedAscending})

例如:

var dict : [String : Any] = ["10" : Any, "2" : Any, "20" : Any, "1" : Any]


dictionary.keys.sorted()

["1" : Any, "10" : Any, "2" : Any, "20" : Any]

dictionary.keys.sorted(by: {$0.localizedStandardCompare($1) == .orderedAscending})

["1" : Any, "2" : Any, "10" : Any, "20" : Any]

按键快速排序字典

因为 Dictionary< sup > [ About ] 是基于 大麻函数的,所以不可能像我们习惯的那样使用排序函数(比如 Array)。作为替代方案,您可以实现一种 Java TreeMap/TreeSet

最简单的方法是使用 .sorted(by:)函数。它返回一个 key/value元组的排序 Array,这很容易处理

例如:

struct Person {
let name: String
let age: Int
}


struct Section {
let header: String
let rows: [Int]
}


let persons = [
Person(name: "A", age: 1),
Person(name: "B", age: 1),
Person(name: "C", age: 1),
Person(name: "A", age: 2),
Person(name: "B", age: 2),
Person(name: "C", age: 2),
Person(name: "A", age: 3),
Person(name: "B", age: 3),
Person(name: "C", age: 3),
]


//grouped
let personsGroupedByName: [String : [Person]] = Dictionary(grouping: persons, by: { $0.name })
/**
personsGroupedByName
[0] = {
key = "B"
value = 3 values {
[0] = (name = "B", age = 1)
[1] = (name = "B", age = 2)
[2] = (name = "B", age = 3)
}
}
[1] = {
key = "A"
value = 3 values {
[0] = (name = "A", age = 1)
[1] = (name = "A", age = 2)
[2] = (name = "A", age = 3)
}
}
[2] = {
key = "C"
value = 3 values {
[0] = (name = "C", age = 1)
[1] = (name = "C", age = 2)
[2] = (name = "C", age = 3)
}
}
*/


//sort by key
let sortedPersonsGroupedByName: [Dictionary<String, [Person]>.Element] = personsGroupedByName.sorted(by: { $0.0 < $1.0 })
/**
sortedPersonsGroupedByName
[0] = {
key = "A"
value = 3 values {
[0] = (name = "A", age = 1)
[1] = (name = "A", age = 2)
[2] = (name = "A", age = 3)
}
}
[1] = {
key = "B"
value = 3 values {
[0] = (name = "B", age = 1)
[1] = (name = "B", age = 2)
[2] = (name = "B", age = 3)
}
}
[2] = {
key = "C"
value = 3 values {
[0] = (name = "C", age = 1)
[1] = (name = "C", age = 2)
[2] = (name = "C", age = 3)
}
}
*/


//handle
let sections: [Section] = sortedPersonsGroupedByName.compactMap { (key: String, value: [Person]) -> Section in
let rows = value.map { person -> Int in
return person.age
}
return Section(header: key, rows: rows)
}
/**
sections
[0] = {
header = "A"
rows = 3 values {
[0] = 1
[1] = 2
[2] = 3
}
}
[1] = {
header = "B"
rows = 3 values {
[0] = 1
[1] = 2
[2] = 3
}
}
[2] = {
header = "C"
rows = 3 values {
[0] = 1
[1] = 2
[2] = 3
}
}
*/

我的意见是,所有的答案似乎都错过了,我们有一个 Dict,我们确实想要一个 Dict:

var menu = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]


let sortedMenu = menu.sorted(by: <) // is an ARRAY
print(type(of: sortedMenu))




let sortedDict = Dictionary( uniqueKeysWithValues: menu.sorted(by: <) )
print(type(of: sortedDict))

上面我按值排序,按键排序:

{(kv1,kv2) in 返回 kv1.key < kv2.key } 和/或使用构造函数将转换应用于 Dect。