假设我有以下两本词典:
dict1 = {vessel1: [a, b, c], vessel2: [a, d, e], ...}
dict2 = {operation1: [a, d], operation2: [a, e, b], ...}
每个字典(dict1
, dict2
)都是字典的字典,因此a
, b
, c
、d
、e
、f
和 g
也是字典。
例如,我想要的是,将 dict1(vessel1)
与 dict2(operation2)
相交,并得到如下结果字典:
result_dictionary_of_intersection = [a, b]
即,有一个结果字典,其中仅包含容器 1 和操作 2 都具有的项目。
记住:a
和 b
也是字典。
最佳答案
这将按您的预期返回 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 使用的内容有更多的灵 active ,您可以这样做(这实际上使代码更具可读性):
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
关于excel - 两个字典相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5406239/