topgun
topgun

Reputation: 2573

Removing Non Duplicate Keys from Two Dictionary

I have two dictionaries in Swift with few similar values which are in dynamic mode:

dict1 = ["a1":"value 1", "b1":"value2", "c1":"value 3"]
dict2 = ["b1": "value2", "d1": "value4"]

If I want to compare these two dictionaries and want to extract only the matching keys even nested, how do I about to do that?

Upvotes: 0

Views: 436

Answers (3)

Alexander
Alexander

Reputation: 63264

As others have shown, you can do this using a filter statement. You can make it even quicker by always filtering the smaller of the two dicts, improving the time complexity from O(dict1.size) to 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))

Upvotes: 1

ielyamani
ielyamani

Reputation: 18581

If you want the common keys with the value in one of them :

let intersectionDict = dict1.filter { dict2.keys.contains($0.key) }
//Or
let intersectionDict2 = dict2.filter { dict1.keys.contains($0.key) }

If you want the values to match too:

let intersectionDict3 = dict1.filter { dict2[$0.key] == $0.value }

And the result is:

print(intersectionDict3)  //["b1": "value2"]

Upvotes: 2

David Pasztor
David Pasztor

Reputation: 54706

You can create a Set from the keys of one of the dictionaries and call intersection on the Set with the keys of the other dictionary.

let matchingKeys = Set(dict1.keys).intersection(dict2.keys) // {"b1"}

Upvotes: 0

Related Questions