我在Swift中有两个字典,在动态模式下有几个相似的值:
dict1 = ["a1":"value 1", "b1":"value2", "c1":"value 3"]
dict2 = ["b1": "value2", "d1": "value4"]
如果我想比较这两个字典并且只想提取甚至嵌套的匹配键,我该怎么做?
答案 0 :(得分:2)
如果您想要其中之一带有值的公用键:
let intersectionDict = dict1.filter { dict2.keys.contains($0.key) }
//Or
let intersectionDict2 = dict2.filter { dict1.keys.contains($0.key) }
如果您也希望这些值也匹配:
let intersectionDict3 = dict1.filter { dict2[$0.key] == $0.value }
结果是:
print(intersectionDict3) //["b1": "value2"]
答案 1 :(得分:1)
如其他人所示,您可以使用filter
语句执行此操作。您可以通过始终过滤两个字典中较小的一个来提高速度,从而将时间复杂度从O(dict1.size)
降低到O(min(dict1.size, dict2.size)
。
extension Dictionary {
func intersectingByKeys(with other: Dictionary) -> Dictionary {
let (smallerDict, largerDict) = (self.count < other.count) ? (self, other) : (other, self)
return smallerDict.filter { key, _ in largerDict.keys.contains(key) }
}
}
let dict1 = ["a1":"value 1", "b1":"value2", "c1":"value 3"]
let dict2 = ["b1": "value2", "d1": "value4"]
print(dict1.intersectingByKeys(with: dict2))
答案 2 :(得分:0)
您可以使用其中一个字典的键创建一个Set
,然后用另一本字典的键调用intersection
上的Set
。
let matchingKeys = Set(dict1.keys).intersection(dict2.keys) // {"b1"}