我有以下字典:
["FLBEY023": ["Position": 8, "Page": 1],
"COSMAX826": ["Position": 6, "Page": 2],
"TOVIC029": ["Position": 7, "Page": 1],
"CGLYN188": ["Position": 2, "Page": 2],
"TOORL002B": ["Position": 1, "Page": 2],
"GSTOGFU096": ["Position": 6, "Page": 1],
"COSNAI423": ["Position": 2, "Page": 1],
"COSCOL681": ["Position": 3, "Page": 2],
"TONIV170": ["Position": 4, "Page": 1],
"SUMAL086A": ["Position": 7, "Page": 2],
"PEIAM004": ["Position": 5, "Page": 1],
"FOSCI012": ["Position": 1, "Page": 1],
"FOSWI009": ["Position": 4, "Page": 2],
"GSTODOV061": ["Position": 3, "Page": 1]]
现在,我想为每个产品代码对此词典进行排序。但我想在位置和页面上对其进行排序。因此,例如我喜欢运行位置然后页码,例如
["FOSCI012": ["Position": 1, "Page": 1],
"COSNAI423": ["Position": 2, "Page": 1],
"GSTODOV061": ["Position": 3, "Page": 1],
....
...
...
"TOORL002B": ["Position": 1, "Page": 2],
"CGLYN188": ["Position": 2, "Page": 2],
..
我将如何使用Dictionary.sorted
方法执行此操作。我理解如何根据一个元素而不是两个元素进行排序。
答案 0 :(得分:4)
字典是无序集合,您无法对它们进行排序。
但是,您可以使用.sorted(by:)
方法返回有序元组列表,其中每个元组表示字典中的键值条目:
dictionary.sorted { (lhs, rhs) -> Bool in
if (lhs.value["Page"]! == rhs.value["Page"]!) {
return lhs.value["Position"]! < rhs.value["Position"]!
} else {
return lhs.value["Page"]! < rhs.value["Page"]!
}
}
导致如下所示:
[(key: "FOSCI012", value: ["Position": 1, "Page": 1]),
(key: "COSNAI423", value: ["Position": 2, "Page": 1]),
...
(key: "TOORL002B", value: ["Position": 1, "Page": 2]),
(key: "CGLYN188", value: ["Position": 2, "Page": 2]),
...
]
答案 1 :(得分:0)
您可以按键和值
对字典进行排序extension Dictionary where Value:Comparable {
var sortedByValue:[(Key,Value)] {return Array(dict).sorted{$0.1 < $1.1}}
}
extension Dictionary where Key:Comparable {
var sortedByKey:[(Key,Value)] {return Array(dict).sorted{$0.0 < $1.0}}
}
["b":2,"a":1,"c":3].sortedByKey// output will be a:1, b:2, c:3
["b":2,"a":1,"c":3].sortedByValue//output will be a:1, b:2, c:3