按键值对字典排序 [英] Sort Dictionary by Key Value

查看:349
本文介绍了按键值对字典排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let dict: [String:Int] = ["apple":5, "pear":9, "grape":1]

如何根据Int值对字典进行排序,以使输出为:

How do you sort the dictionary based on the Int value so that the output is:

sortedDict = ["pear":9, "apple":5, "grape":1]

当前尝试(排序不正确):

let sortedDict = sorted(dict) { $0.1 > $1.1 } 

推荐答案

您需要对字典值而不是键进行排序.您可以从字典中创建一个元组数组,按其值对它进行排序,如下所示:

You need to sort your dictionary values, not your keys. You can create an array of tuples from your dictionary sorting it by its values as follow:

Xcode 9•Swift 4 Xcode 8•Swift 3

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


使用键对字典进行排序


To sort your dictionary using your keys

let fruitsTupleArray = fruitsDict.sorted{ $0.key > $1.key }
fruitsTupleArray  // [(key "pear", value 9), (key "grape", value 1), (key "apple", value 5)]

要使用字典的键和本地化的比较来对字典进行排序:

To sort your dictionary using its keys and localized comparison:

let fruitsTupleArray = fruitsDict.sorted { $0.key.localizedCompare($1.key) == .orderedAscending  }

这篇关于按键值对字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆