【问题标题】:Sort Dictionary by Key Based on Values in Array根据数组中的值按键对字典进行排序
【发布时间】:2015-03-22 20:10:39
【问题描述】:

如何按照数组中列出的顺序对字典进行排序?见例子:

要排序的字典:

var item = [
    "itemName":"radio",
    "description":"battery operated",
    "qtyInStock":"12",
    "countOfChildren":"5",
    "isSerialized":"0"
]

键的排序顺序:

let sortOrder = [
    "itemName",
    "qtyInStock",
    "countOfChildred",
    "description",
    "isSerialized"
]

我在 Playground 中尝试过以下操作:

var sortedItem = Dictionary<String, String>()

for i in sortOrder {
    sortedItem[i] = item[i]
}

在 Playground 中查看值历史记录以正确的顺序显示所有内容时,生成的字典的顺序看似随机。

【问题讨论】:

    标签: arrays sorting swift dictionary


    【解决方案1】:

    正如 Tiago 所提到的,Dictionary 根据定义没有订单。它本质上是键到值的映射。我会推荐两种方法之一。

    如果您希望实现的排序是手动的,因为您的问题看起来如此。我会创建一个数组来保存有序键。然后,在您需要的任何时候,您可以循环遍历数组(即顺序)并打印出字典中找到的所有值。它们本质上会使用有序的键数组打印出来。

    如果排序不是以编程方式完成的,您可以通过 myDictionary.keys.array 获取对所有键的引用。然后您可以对数组进行排序,然后再次遍历数组并从字典中获取值。

    例子:

    let myKeys = myDictionary.keys.array
    // sort the keys
    for key in myKeys {
        println(myDictionary[key])
    }
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      根据定义,字典没有顺序。

      但是,您可以使用 array of sorted items by touplesimplement your sorted dictionary

      【讨论】:

        猜你喜欢
        • 2016-04-17
        • 1970-01-01
        • 1970-01-01
        • 2011-12-11
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多