2013-09-01 43 views
42

我正在通过倒排索引搜索程序。索引本身是一个字典,其中的键是术语,其值本身是短文档的字典,ID编号为键,文本内容为值。在Python中相交两个词典

为了对两个词进行'AND'搜索,我需要将他们的发布列表(词典)相交。什么是明确的(不一定非常聪明)的方式在Python中做到这一点?我开始试图通过它的很长的路要走与iter

p1 = index[term1] 
p2 = index[term2] 
i1 = iter(p1) 
i2 = iter(p2) 
while ... # not sure of the 'iter != end 'syntax in this case 
... 
+0

{i:dict(p1 [i],* * p2 [i])for i in p1 if if in p2} – mtadd

+0

我的上面的评论会与您的词典词典相交,但是联盟合并您的发布列表....如果您还想将您的发帖列表与您的文档ID号码相交,你可以在p1 [term]中使用'{term:{doc_id:p1 [term] [doc_id] for doc_id in p2 [term]} for term in p1} – mtadd

回答

43

您可以轻松地计算出的集合的交集,所以创建密钥集,并利用它们的交集:

keys_a = set(dict_a.keys()) 
keys_b = set(dict_b.keys()) 
intersection = keys_a & keys_b # '&' operator is used for set intersection 
2

只是包装用一个简单的类,既得到你想要的值的字典实例

class DictionaryIntersection(object): 
    def __init__(self,dictA,dictB): 
     self.dictA = dictA 
     self.dictB = dictB 

    def __getitem__(self,attr): 
     if attr not in self.dictA or attr not in self.dictB: 
      raise KeyError('Not in both dictionaries,key: %s' % attr) 

     return self.dictA[attr],self.dictB[attr] 

x = {'foo' : 5, 'bar' :6} 
y = {'bar' : 'meow' , 'qux' : 8} 

z = DictionaryIntersection(x,y) 

print z['bar'] 
+5

为什么我要写所有的代码?如果我这样做,我不会在python编码,但Java! :) –

79

一个鲜为人知的事实是,你并不需要构建set s到这样做:

在Python 2:

In [78]: d1 = {'a': 1, 'b': 2} 

In [79]: d2 = {'b': 2, 'c': 3} 

In [80]: d1.viewkeys() & d2.viewkeys() 
Out[80]: {'b'} 

在Python 3与keys替换viewkeys;这同样适用于viewvaluesviewitems

viewitems文档:

In [113]: d1.viewitems?? 
Type:  builtin_function_or_method 
String Form:<built-in method viewitems of dict object at 0x64a61b0> 
Docstring: D.viewitems() -> a set-like object providing a view on D's items 

对于较大dict s此也略快于构建set秒,然后交叉他们:

In [122]: d1 = {i: rand() for i in range(10000)} 

In [123]: d2 = {i: rand() for i in range(10000)} 

In [124]: timeit d1.viewkeys() & d2.viewkeys() 
1000 loops, best of 3: 714 µs per loop 

In [125]: %%timeit 
s1 = set(d1) 
s2 = set(d2) 
res = s1 & s2 

1000 loops, best of 3: 805 µs per loop 

For smaller `dict`s `set` construction is faster: 

In [126]: d1 = {'a': 1, 'b': 2} 

In [127]: d2 = {'b': 2, 'c': 3} 

In [128]: timeit d1.viewkeys() & d2.viewkeys() 
1000000 loops, best of 3: 591 ns per loop 

In [129]: %%timeit 
s1 = set(d1) 
s2 = set(d2) 
res = s1 & s2 

1000000 loops, best of 3: 477 ns per loop 

我们在这里比较纳秒,这可能或者可能对你无关紧要。无论如何,你得到一个set,所以使用viewkeys/keys消除了一点混乱。

+4

'viewkeys()'是“2.7版本中的新功能” –

+0

不知何故,这最终会比* set(d1.keys())&set(d2 .keys())'方法。但是,我不明白为什么会这样。 – Dan

+0

@Dan:即使它(可能)更慢,它看起来更多* Pythonic *对我来说 –

43
In [1]: d1 = {'a':1, 'b':4, 'f':3} 

In [2]: d2 = {'a':1, 'b':4, 'd':2} 

In [3]: d = {x:d1[x] for x in d1 if x in d2} 

In [4]: d 
Out[4]: {'a': 1, 'b': 4} 
+8

这应该是答案,因为这是唯一一个以简单的方式显示如何获得交叉点字典而不是键列表的方法。 – Rafe

1

好的,这里是Python3中以上代码的通用版本。 它被优化使用足够快的理解和set-like字典视图。

功能相交任意许多类型的字典并返回与公共密钥的字典和每个公用密钥的一组共同的值:

def dict_intersect(*dicts): 
    comm_keys = dicts[0].keys() 
    for d in dicts[1:]: 
     # intersect keys first 
     comm_keys &= d.keys() 
    # then build a result dict with nested comprehension 
    result = {key:{d[key] for d in dicts} for key in comm_keys} 
    return result 

用例:

a = {1: 'ba', 2: 'boon', 3: 'spam', 4:'eggs'} 
b = {1: 'ham', 2:'baboon', 3: 'sausages'} 
c = {1: 'more eggs', 3: 'cabbage'} 

res = dict_intersect(a, b, c) 
# Here is res (the order of values may vary) : 
# {1: {'ham', 'more eggs', 'ba'}, 3: {'spam', 'sausages', 'cabbage'}} 

这里字典的值必须如果他们不是你可以简单地将圆括号{}改为列表[]:

result = {key:[d[key] for d in dicts] for key in comm_keys} 
+0

我正在向函数传递一个字典列表,但它给出错误。我如何编辑上面的函数,以便字典的alist被传递,并且key:具有常用键的值对以及值被获得? – learnningprogramming

+0

@learnningprogramming,希望你已经想出了如何解决这个问题,但是对于其他人来说好奇:'* dicts'作为函数参数意味着你需要传递许多参数,而不是它们的列表。如果你有'lst = [dict1,dict2,dict3,...]'或者使用'dict_intersect(dict1,dict2,dict3,...)'或者解压列表'dict_intersect(* lst)' – thodnev