python - 比使用集合更快的比较字典的方法

标签 python dictionary set

我有两个大字典,它们具有唯一的键,但可能存在重叠的值。我想将每组字典值相互比较并找到重叠的数量。我已经使用两个 for 循环和 set 完成了此操作,但我想知道是否有更快/更优雅的方法来执行此操作。

dic1 = {'a': ['1','2','3'], 'b':['4','5','6'], 'c':['7','8','9']}
dic2 = {'d': ['1','8','9'], 'e':['10','11','12'], 'f':['7','8','9']}

final_list=[]
for key1  in dic1:
    temp=[]    
    for key2 in dic2:
        test  = set(dic1[key1])
        query = set(dic2[key2])
        x = len(test & query)
        temp.append( [key2, x] )
    final_list.append([key1, temp])

最佳答案

您想要“反转”一本(或两本)字典。

val1 = defaultdict(list)
for k in dic1:
    for v in dic1[k]:
        val[v].append( k )
# val1 is a dictionary with each value mapped to the list of keys that contain that value.

for k in dic2: 
    for v in dic2[k]:
        val1[v] is the list of all keys in dic1 that have this value

关于python - 比使用集合更快的比较字典的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8649802/

相关文章:

jenkins - 读取控制台日志行/值后设置 Jenkins 变量 -- 或者 -- 使用 Jenkins 调用的脚本/命令使用的变量

java - 是否可以将 Set 转换为 List?

java - 使用 Set - 自动删除重复项?

python - 是否使用正则表达式将字符串替换为字典值列表中的键

python - Pandas 中的字符串包含

python - 为什么python字典会改变顺序?

Python 从列表中的搜索导出新的字典

Python subprocess.call 在没有 shell=True 的情况下不起作用

python - 查找修改后的图像 - 图像取证

python - 从字典中查找随机选择的键的值