【问题标题】:How to sum the Value from the same Key using a Dictionary?如何使用字典对同一键的值求和?
【发布时间】:2019-12-05 00:23:22
【问题描述】:

我有一本看起来像这样的字典:

(value: 21.0, id: "JdknnhshyrY56AXQcAiLcYtbVlz2") ---> This has a second entry
(value: 18.0, id: "nIvb519nNfMtlVNnsQJ5w4bRbFp2")
(value: 14.0, id: "tlKqcxHdPoemwGqJsyLhERnuQ3Z2")
(value: 5.0,  id: "JdknnhshyrY56AXQcAiLcYtbVlz2")]---> This is the second entry

如果有重复条目,我想将值添加到相同的 id。 像这样:

(value: 26.0, id: "JdknnhshyrY56AXQcAiLcYtbVlz2") ---> Value has added and key has become only one
(value: 18.0, id: "nIvb519nNfMtlVNnsQJ5w4bRbFp2")
(value: 14.0, id: "tlKqcxHdPoemwGqJsyLhERnuQ3Z2")]

我已经尝试过使用 map 方法,但一直在工作,已经添加了值,但 id 上的多个条目仍然保持多个。

我怎样才能达到这个结果。

【问题讨论】:

  • 它是一个字典数组吗?

标签: swift sorting dictionary


【解决方案1】:

始终建议将您的Dictionary(与异构 最终落入[AnyHashable : Any] 的值类型 category) 到 Typed 对象。使用类型化的对象、操作或 其他计算变得方便。

在上述陈述的前提下,你会做这样的事情:

let objects = [Object]() // this would be you array with actual data
let reduced = objects.reduce(into: [Object]()) { (accumulator, object) in
    if let index = accumulator.firstIndex(where: { $0.id == object.id }) {
        accumulator[index].value += object.value
    } else {
        accumulator.append(object)
    }
}

Object 在哪里:

struct Object {
    var value: Double
    let id: String
}

现在,如果您想知道如何将 Dictionary 转换为 & from Object 类型,请查看完整代码:

let arrayOfDictionary = [["value": 21.0, "id": "JdknnhshyrY56AXQcAiLcYtbVlz2"],
                         ["value": 18.0, "id": "nIvb519nNfMtlVNnsQJ5w4bRbFp2"],
                         ["value": 14.0, "id": "tlKqcxHdPoemwGqJsyLhERnuQ3Z2"],
                         ["value": 5.0,  "id": "JdknnhshyrY56AXQcAiLcYtbVlz2"]]

struct Object: Codable {
    var value: Double
    let id: String
}

do {
    let jsonData = try JSONSerialization.data(withJSONObject: arrayOfDictionary, options: [])
    let objects = try JSONDecoder().decode([Object].self, from: jsonData)

    let reduced = objects.reduce(into: [Object]()) { (accumulator, object) in
        if let index = accumulator.firstIndex(where: { $0.id == object.id }) {
            accumulator[index].value += object.value
        } else {
            accumulator.append(object)
        }
    }

    let encodedObjects = try JSONEncoder().encode(reduced)
    let json = try JSONSerialization.jsonObject(with: encodedObjects, options: [])
    if let reducedArrayOfDictionary = json as? [[String : Any]] {
        print(reducedArrayOfDictionary)
    }
} catch {
    print(error)
}

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多