ios - iOS swift 4 sort dictionary by a particular values
问题描述
Can you please help me sorting the dictionary below with value "Val1".
var data = ["key1" : ["val1": 1,"val2": 1],
"key2" : ["val1": 5,"val2": 2],
"key3" : ["val1": 0,"val2": 9]]
I am expecting this dictionary to be sorted like this. Highest values of 'Val1' to be on top (descending order)..
var data = [ "key2" : ["val1": 5,"val2": 2],
"key1" : ["val1": 1,"val2": 1],
"key3" : ["val1": 0,"val2": 9]]
解决方案
As @Sulthan correctly pointed out Dictionary
cannot be sorted. If you still want to, you'll get an Array
as result.
let data = [
"key1": ["val1": 1,"val2": 1],
"key2": ["val1": 5,"val2": 2],
"key3": ["val1": 0,"val2": 9]
]
let result = data.sorted { $0.1["val1"]! > $1.1["val1"]! }
print(result)
[(key: "key2", value: ["val1": 5, "val2": 2]), (key: "key1", value: ["val1": 1, "val2": 1]), (key: "key3", value: ["val1": 0, "val2": 9])]
推荐阅读
- sql - 计算来自多个表的连接数
- arrays - 将链接二叉树转换为基于数组的二叉树
- c# - Unity 没有将组件变量识别为组件
- javascript - React Native中通过axios上传图片
- ruby-on-rails - Ruby on Rails 帮助了解如何查找方法的来源
- laravel - 如何在 yajra 数据表 laravel 中添加操作列
- ethereum - 如何从 Truffle 控制台与 OpenZeppelin 代理合约进行交互?
- reactjs - React useEffect 从数据库中获取数据但没有及时在组件中使用
- gatling - Gatling 脚本工作正常,但打印 jldLagartoDOMBuilderTagVisitor - Unclosed tag closed:
- c - 分配字符串与分配结构的字段