好的,這裏是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