好的,这里是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}
{i:dict(p1 [i],* * p2 [i])for i in p1 if if in p2} – mtadd
我的上面的评论会与您的词典词典相交,但是联盟合并您的发布列表....如果您还想将您的发帖列表与您的文档ID号码相交,你可以在p1 [term]中使用'{term:{doc_id:p1 [term] [doc_id] for doc_id in p2 [term]} for term in p1} – mtadd