查找具有匹配键的字典的值的总和

Finding the sum of the values of a dictionary with matching keys

我有一个 [String: [String: Int]] 类型的嵌套字典,如下所示:

var dict = [
    "A": ["a": 234, "b": 322],
    "B": ["c": 45, "d": 443],
    "C": ["b": 50, "e": 940, "f": 9430, "a": 53029]
]

我想转换它,以便将所有相同小写键的整数加在一起形成另一个字典:

["a": 53263, "b": 382, "c": 45, "d": 50, "e": 940, "f": 9430]

我不喜欢钥匙 "A", "B", "C"

首先,我映射dict以提取嵌套字典:

let result1 = dict.map {  }
// [["b": 322, "a": 234], ["c": 45, "d": 443], ["e": 940, "b": 50, "a": 53029, "f": 9430]]

我用 flatMap 得到元组:

let result2 = dict.map {  }.flatMap { [=13=].map { [=13=] }}
// [(key: "c", value: 45), (key: "d", value: 443), (key: "f", value: 9430), (key: "e", value: 940), (key: "a", value: 53029), (key: "b", value: 50), (key: "a", value: 234), (key: "b", value: 322)]

最后,我尝试使用 result2 并映射每个项目以添加相同键的所有值和 return 类型 [String: Int]:[=22= 的字典]

var tempArray = [String]()
var finalDict = [String: Int]()
var count = 0
let result3 = dict.map {  }.flatMap { [=14=].map { el -> [String: Int] in
    if tempArray.contains(el.key) {
        if let newCount = finalDict[el.key] {
            count += newCount
            finalDict[el.key] = newCount
        }
    } else {
        tempArray.append(el.key)
        finalDict = [el.key: el.value]
    }

    return finalDict
}}

但是,我得到的结果是:

[["b": 322], ["a": 234], ["c": 45], ["d": 443], ["d": 443], ["d": 443], ["f": 9430], ["e": 940]]

显示多个相同的键。

你快到了。 result2 是一个元组数组,您可以使用它通过添加它们的值来构造具有唯一键的字典:

var dict = Dictionary(result2, uniquingKeysWith: +)

这将为您提供所需的东西(不保证订单):

["c": 45, "a": 53263, "d": 443, "b": 372, "f": 9430, "e": 940]

有一种稍微简单的方法来获取您的 result2:

let result2 = dict.flatMap { [=12=].value }.flatMap { [=12=].map{ [=12=] } }

您可以将 dict 转换为字典数组,然后使用 reduce 合并键。

let values = dict.map {[=10=].value}.flatMap {[=10=]}

let merged = values .flatMap{[=10=]}.reduce([String:Int]()) { (previous, dict) in
    var newDict = previous
    if let lastValue = previous[dict.key] {
        let sum = lastValue + dict.value
        newDict[dict.key] = sum
    } else {
        newDict.updateValue(dict.value, forKey: dict.key)
    }
    return newDict
}

print(merged)

您可以使用 flatMap 创建一个元组数组,然后 reduce(into:) 使用键和每个键的值之和创建字典

let result = dict.values
    .flatMap {[=10=]}
    .reduce(into: [:]) { [=10=][.key, default: 0] += .value }

你可以使用字典 uniquingKeysWith 初始值设定项并使用 plus 方法将它们相加:


let result: Dictionary = .init(dict.flatMap(\.value), uniquingKeysWith: +)