交集两个字典

3

假设我有以下两个字典:

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

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

每个字典(dict1dict2)都是一个字典的字典,所以abcdefg也是字典。
我想要的是,例如将dict1(vessel1)dict2(operation2)相交,并得到以下结果字典:
result_dictionary_of_intersection = [a, b]

即,需要一个结果字典,其中仅包含船只1和操作2都拥有的项目。
记住:ab也是字典。

1
无需在标题中添加标签。 - user1228
我不清楚您所说的交叉字典是什么意思。如果您想使用类似于集合的字典,请参见:https://dev59.com/IlPTa4cB1Zd3GeqPkZKi#4751101。假设[a,b,c]和[a,e,b]表示列表(或集合,数组等),并且每个列表中的a,b等都是相同的字典*实例*,那么这将完美地运行。 - jtolle
2个回答

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
我曾以为VBA会有一个内置的交集方法,但我现在了解到,即使是一个简单的排序列表函数也很难从VBA中获得。 - Gabriel L. Oliveira
1
是的,VBA有一些相当严重的限制。 - Stewbob

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接