相交两个词典

时间:2011-03-23 13:51:06

标签: excel vba dictionary intersection

假设我有两个词典如下:

dict1 = {vessel1: [a, b, c], vessel2: [a, d, e], ...}

dict2 = {operation1: [a, d], operation2: [a, e, b], ...}

每个字典(dict1dict2)都是字典字典,因此abcd, <{1}},ef也是字典。

我想要的是,例如,将gdict1(vessel1)相交,并拥有如下结果字典:

dict2(operation2)

即,有一个结果字典只包含vessel1和operation2都有的项目。

记住:result_dictionary_of_intersection = [a, b] a也是字典。

2 个答案:

答案 0 :(得分:2)

这将按照您的意图返回a和b词典。这假定vessel1字典的键是字符串“vessel1”,而operation2字典的键是“operation2”。当然,您可以使用代码中的变量替换这些字符串文字。

Dim newDict As Dictionary
Set newDict = New Dictionary

For Each myKey In dict1("vessel1").Keys

   If dict2("operation2").Exists(myKey) Then
        newDict.Add myKey, dict2("operation2")(myKey)
   End If

Next

如果你想对dict1和dict2使用的内容有一点灵活性,你可以这样做(这实际上使代码更具可读性):

Set tmpDict1 = dict1("vessel1")
Set tmpDict2 = dict2("operation2")

Dim newDict As Dictionary
Set newDict = New Dictionary

For Each myKey In tmpDict1.Keys

   If tmpDict2.Exists(myKey) Then
        newDict.Add myKey, tmpDict2(myKey)
   End If

Next

答案 1 :(得分:0)

您可能会觉得这很有用:

Sub testMe()
Dim dict1 As New Dictionary
Dim dict2 As New Dictionary
Dim dict3 As New Dictionary

Dim dictAll As New Dictionary
Dim dictUnion As New Dictionary
Dim dictTemp As New Dictionary

dict1.Add "A", "A"
dict1.Add "B", "B"
dict1.Add "C", "C"
dict1.Add "D", "D"
dict1.Add "E", "E"

dict2.Add "C", "C"
dict2.Add "D", "D"
dict2.Add "E", "E"
dict2.Add "F", "F"

dict3.Add "C", "C"
dict3.Add "D", "D"

dictAll.Add 1, dict1
dictAll.Add 2, dict2
dictAll.Add 3, dict3

Dim var As Variant
Dim i As Integer

Set dictUnion = dictAll(1)

For Each var In dictAll
    Set dictTemp = dictAll(var)
    Set dictUnion = intMe(dictUnion, dictTemp)
Next

'Set dictUnion = intMe(dict1, dict2)
For Each var In dictUnion
    Debug.Print var
Next

Set dict1 = Nothing
Set dict2 = Nothing
Set dict3 = Nothing
Set dictAll = Nothing
Set dictUnion = Nothing
Set dictTemp = Nothing

End Sub

Function intMe(dict1 As Dictionary, dict2 As Dictionary) As Dictionary
Dim dictInt As New Dictionary
Dim var As Variant
For Each var In dict1.Keys
    If dict2.Exists(var) Then
        dictInt.Add var, var
    End If
Next
Set intMe = dictInt
End Function

Sub Intersect(dAll As Dictionary)

Dim var As Variant
Dim subVar As Variant
Dim dict As Dictionary

For Each var In dAll

    If var <> "Account_LV0" And var <> "Account_LV1" Then


        Set dict = dAll(var)
        Debug.Print var & "|" & dict.Count
        'For Each subVar In dict.Keys
        '    Debug.Print subVar
        'Next
    End If
Next


End Sub