VBA and Python – Intersection of dictionaries

Intersection of dictionary (or of any two lists) is a list with elements, that are present in both other lists.

A random tree.

Thus, if we have the following 3 dictionaries in Python:

dict_a = dict([('aa', 4139), ('bb', 4127), ('cc', 4098)])
dict_b = dict(aa=4139, bb=4127, ee=4098)
dict_c = {'aa':12, 'bb':13, 'dd':23}

Then, an intersection of their keys will contain only aa and bb , as these are the only keys, present in each one of them. With Python, making an intersection, union or a difference is actually quite easy. You need only 1 single binary operator and it works:

intersection = dict_a.keys() & dict_b.keys() & dict_c.keys()
union = dict_a.keys() | dict_b.keys() | dict_c.keys()
difference = dict_a.keys() ^ dict_b.keys()

However, with VBA (I bet 10 beers, this is the only article in the whole net, comparing VBA with Python, based on dictionary intersection) the story is not that charming. You will probably need a whole function for this. I have built a function, returning an empty dictionary, with keys that are intersection of the keys of 2 input dictionaries:

Public Function IntersectTwoDictionaries(dictA As Dictionary, dictB As Dictionary) As Dictionary

    Dim newDictionary As New Dictionary
    Dim myKey As Variant
    
    For Each myKey In dictA.Keys
        If dictB.Exists(myKey) Then
            newDictionary.Add myKey, Nothing
        End If
    Next
    
    Set IntersectTwoDictionaries = newDictionary

End Function

That’s all, folks!