Swift:合并具有重复键但唯一值的字典数组

时间:2020-01-31 16:18:14

标签: ios swift dictionary swift5 swift5.1

我有一个字典数组,其中包含相同的键但值不同。我想合并这些字典并添加相同键的所有值,如下所示:

var arrayofDict = [["2019":"A"],["2019":"B"],["2019":"C"],["2018":"A"],["2018":"c"],["2017":"A"],["2017":"B"],["2017":"C"],["2016":"A"],["2015":"A"],["2015":"B"]]

预期结果为字典:

   var newDict = [["2019":["A","B","C"]],["2018":["A","C"]],["2017":["A","B","C"]],["2016":["A"]],["2015":["A","B"]]]

2 个答案:

答案 0 :(得分:3)

这显示了如何构建单个词典。您的“预期结果”是一个数组。这是您真正期望的,还是想要一个数组?

您可以迭代字典项并建立字典条目:

var arrayofDict = [["2019":"A"],["2019":"B"],["2019":"C"],["2018":"A"],["2018":"c"],["2017":"A"],["2017":"B"],["2017":"C"],["2016":"A"],["2015":"A"],["2015":"B"]]

var result = [String : [String]]()
for dict in arrayofDict {
    for (key, value) in dict {
        result[key, default: []].append(value)
    }
}

print(result)
["2016": ["A"], "2018": ["A", "c"], "2015": ["A", "B"], "2019": ["A", "B", "C"], "2017": ["A", "B", "C"]]

或者,如果需要阵列:

let result2 = result.map { [$0.key: $0.value] }
print(result2)
[["2015": ["A", "B"]], ["2016": ["A"]], ["2019": ["A", "B", "C"]], ["2018": ["A", "c"]], ["2017": ["A", "B", "C"]]]

答案 1 :(得分:0)

以更实用的方式用作@vacawama

let result = arrayofDict.reduce(into: [String:[String]]()) { (acc, d) in
    for key in d.keys {
        // don't worry to force unwrap d[key], if key exist, the value is not nil
        acc[key, default: []].append(d[key]!)
    }
}