【问题标题】:Converting two dicts into one dict as key value pair in Swift将两个字典转换为一个字典作为 Swift 中的键值对
【发布时间】:2020-07-26 10:00:58
【问题描述】:

假设我有两个字典: dictA = [1 : 7, 2 : 3, 3 : 4]dictB = [1 : Car, 2 :Banana, 3 : Apple]

如何制作像这样的新字典:dictAB =[Car : 7, Banana : 3, Apple : 4]

如您所见,我想创建一个新字典,对于两个字典中的相同键,从两个初始值生成一个新键值对,因此字典中的键有点用作一个索引。

感谢您的帮助。 :)

【问题讨论】:

  • 你一定尝试过什么?请分享您迄今为止的努力。

标签: ios swift dictionary


【解决方案1】:

首先,确定两个字典共有的键集。然后,使用这些键组装一个新字典:

let dictA = [1 : 7, 2 : 3, 3 : 4]
let dictB = [1 : "Car", 2: "Banana", 3: "Apple"]
let dictAB = ["Car": 7, "Banana": 3, "Apple": 4]

let commonKeys = Set(dictA.keys).intersection(dictB.keys)
let temp = commonKeys.map { (dictB[$0]!, dictA[$0]!) }
let result = Dictionary(temp, uniquingKeysWith: {v1, v2 in v2} )

print(result) // ["Banana": 3, "Apple": 4, "Car": 7]
print(result == dictAB) // true

【讨论】:

    【解决方案2】:

    你可以试试:

    let dictAB = Dictionary(uniqueKeysWithValues: dictB.map { ($0.value, dictA[$0.key]) })
    

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 2019-07-18
      • 1970-01-01
      相关资源
      最近更新 更多