按键值对字典排序
let dict: [String:Int] = ["apple":5, "pear":9, "grape":1]
如何根据Int
值对字典进行排序,以便输出为:
sortedDict = ["pear":9, "apple":5, "grape":1]
当前尝试(排序不正确):
let sortedDict = sorted(dict) { $0.1 > $1.1 }
回答:
您需要对字典值而不是键进行排序。您可以从字典中创建一个元组数组,按其值对它进行排序,如下所示:
或
let fruitsDict = ["apple": 5, "pear": 9, "grape": 1]let fruitsTupleArray = fruitsDict.sorted{ $0.value > $1.value }
fruitsTupleArray // [(.0 "pear", .1 9), (.0 "apple", .1 5), (.0 "grape", .1 1)]
for (fruit,votes) in fruitsTupleArray {
print(fruit,votes)
}
fruitsTupleArray.first?.key // "pear"
fruitsTupleArray.first?.value // 9
使用按键对字典进行排序
let fruitsTupleArray = fruitsDict.sorted{ $0.key > $1.key }fruitsTupleArray // [(key "pear", value 9), (key "grape", value 1), (key "apple", value 5)]
使用字典的键和本地化的比较来对字典进行排序:
let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending }
以上是 按键值对字典排序 的全部内容, 来源链接: utcz.com/qa/401817.html