2011-12-27 42 views
1

我有两个带有唯一键的大字典,但可能有重叠的值。我想比较每组字典值彼此并找出重叠的数量。我已经完成了这两个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]) 
+0

最后一行出现错误。你的意思是'final_list.append([key1,temp])'?确实是 – 2011-12-27 22:13:30

+0

。接得好。 – zach 2011-12-27 22:15:54

+0

你真的在比较dic1中的每个键与dic2中的每个键吗?这就是他们所说的** O ** n^2。这本质上很慢。 – 2011-12-27 22:30:12

回答

2

你想“倒置”一个(或两个)你的字典。

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 
+0

我喜欢这个想法。我认为它会很好地工作,因为我的两本字典大小不同。我可以“倒置”小的一个,并通过大的一个循环。 – zach 2011-12-27 22:57:02

+1

@zach:完全向后。反转大的一个。循环通过小的一个。它会更快。 – 2011-12-28 02:21:09