能否请您帮我对下面的字典中的值“ Val1”进行排序。
var data = ["key1" : ["val1": 1,"val2": 1],
"key2" : ["val1": 5,"val2": 2],
"key3" : ["val1": 0,"val2": 9]]
我希望这本字典能像这样排序。最高的“ Val1”值位于顶部(降序)。
var data = [ "key2" : ["val1": 5,"val2": 2],
"key1" : ["val1": 1,"val2": 1],
"key3" : ["val1": 0,"val2": 9]]
答案 0 :(得分:1)
正如@Sulthan正确指出的,Dictionary
无法排序。如果仍然愿意,您会得到Array
的结果。
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]), (键:“ key1”,值:[“ val1”:1,“ val2”:1]), (键:“ key3”,值:[“ val1”:0,“ val2”:9])]