excel - 两个字典相交

标签 excel vba dictionary intersection

假设我有以下两本词典:

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

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

每个字典(dict1, dict2)都是字典的字典,因此a, b, cdefg 也是字典。

例如,我想要的是,将 dict1(vessel1)dict2(operation2) 相交,并得到如下结果字典:

result_dictionary_of_intersection = [a, b]

即,有一个结果字典,其中仅包含容器 1 和操作 2 都具有的项目。

记住:ab 也是字典。

最佳答案

这将按您的预期返回 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/

相关文章:

excel - 模糊 'Countif' excel公式

python - 如果 df1 中的工作表名称与字符串值匹配,我如何将 df2 复制到 df1

vba - Excel VBA : Compile Error: Method or data member not found

arrays - 当有集合时,为什么在 VBA 中使用数组?

python - 遍历包含元组的字典

c# - 在字典内部的字典中添加键值对

python - Pandas 写入 excel : 1) blank row from index; 2) keep index daily

C# 和 Excel - 对行进行分组并移动加号/减号图标

vba - 尝试在Err.Clear中使用On Error GoTo <label>

python - 附加到具有字典理解的列表字典