将字典数组转换为字典

时间:2019-05-07 06:28:57

标签: arrays swift dictionary

[
  [
    "firstname":"Gary","age":35,"lastname":"Jon","marks": 
      [
        "English":98,"Maths":45,"Science":58,"Social":95
      ],
    "section":"A"
  ], 
  [
    "firstname":"Jacob","age":32,"lastname":"bil","marks": 
      [
        "English":90,"Maths":65,"Science":88,"Social":90
      ],
    "section":"B"
  ]
]

如何将上面的词典数组转换成包含名字和姓氏以及总成绩的字典?
这是预期的结果:

[Gary Jon: 296, Jacob bil: 333]

1 个答案:

答案 0 :(得分:1)

您可以尝试一下,

let d = [
    ["firstname":"Gary","age":35,"lastname":"Jon","marks":["English":98,"Maths":45,"Science":58,"Social":95],"section":"A"],
    ["firstname":"Jacob","age":32,"lastname":"bil","marks":["English":90,"Maths":65,"Science":88,"Social":90],"section":"B"]
]

let dd = d.reduce([:]) { (result, value) -> [String: Int] in
    let marks = value["marks"] as! [String: Int]
    let totalMarks = marks.values.reduce(0, +)

    let firstName = value["firstname"] as! String
    let lastName = value["lastname"] as! String

    let student = ["\(firstName) \(lastName)" : totalMarks]
    return result.merging(student) { $1 }
}
print(dd)

输出

["Gary Jon": 296, "Jacob bil": 333]