如何将基于相似键的字典分成几组,然后用更新的键创建这些组的数组?

时间:2019-01-24 16:17:15

标签: arrays swift dictionary grouping

我有一本词典,其关键字后面附加了_0,_1,_2。

let dict = ["a_0":"0", "b_1":"1", "c_0":"2", "d_2":"3"]

我想对每个键都使用类似的下划线和数字,然后将它们与其他键分开放置。任何带有_0的键都应该在一个组中,在另一个组_1中,在另一个组_2中...

let arrOfGroupedDictsWithSimilarKeys = [["a_0":"0", "c_0":"2"], ["b_1":"1", ], ["d_2":"3"] ]

然后我想通过删除所有键中的下划线和数字来更新每个组中的键,但仍将所有内容保留在其组中。

结果应该是

let arrOfGroupedDictsWithKeysChanged = [["a":"0", "c":"2"], ["b":"1"], ["d":"3"] ]

2 个答案:

答案 0 :(得分:3)

func transformDict(dict: [String: String]) -> [[String: String]] {
    var temp: [String: [String: String]] = [:]
    for (key, value) in dict {
        let components = key.components(separatedBy: "_")
        if components.count == 2 {
            let groupKey = components[1]
            let dictKey = components[0]
            if temp[groupKey] != nil {
                temp[groupKey]?[dictKey] = value
            } else {
                temp[groupKey] = [dictKey: value]
            }
        }
    }

    let res = Array(temp.values)
    return res
}

let res = transformDict(dict: ["a_0":"0",
                               "b_1":"1",
                               "c_0":"2",
                               "d_2":"3"])
print(res)

答案 1 :(得分:0)

另一种相似的方式:

let dict = ["a_0":"0", "b_1":"1", "c_0":"2", "d_2":"3"]

 let result = Dictionary(grouping: dict)
              {(key, value) ->  String in return key.components(separatedBy: "_").last!}.values
              .map{Dictionary(uniqueKeysWithValues:$0.map{($0.key.components(separatedBy: "_").first!, $0.value)})}

print (result)

  // [["c": "2", "a": "0"], ["d": "3"], ["b": "1"]]