一种但不是很高效的处理长字典的方法是使用
itertools.combinations
来查找字典之间的组合,然后在组合和集合之间循环,并获取集合项之间的交集。
one = {'one':{'A':'m','B':'n','C':'o'}}
two ={'two':{'A':'m','B':'n','C':'p'}}
three = {'three':{'A':'x','B':'n','C':'p'}}
dict_list=[one,two,three]
v_item=[i.items() for i in dict_list]
from itertools import combinations
names=[]
items=[]
l=[combinations(v_item,i) for i in range(2,4)]
flat=[[[t[0] for t in k] for k in j] for j in l]
"""this line is for flattening the combinations i don't know why but python puts every elements within a list :
>>> l
[[([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('two', {'A': 'm', 'C': 'p', 'B': 'n'})]),
([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})]),
([('two', {'A': 'm', 'C': 'p', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})])],
[([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('two', {'A': 'm', 'C': 'p', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})])]]"""
for comb in flat :
for pair in comb:
names,items =zip(*pair)
items=[i.viewitems() for i in items]
print names,reduce(lambda x,y:x&y,items)
结果:
('one', 'two') set([('B', 'n'), ('A', 'm')])
('one', 'three') set([('B', 'n')])
('two', 'three') set([('B', 'n'), ('C', 'p')])
('one', 'two', 'three') set([('B', 'n')])
关于下面的这几行:
items=[i.viewitems() for i in items]
print names,reduce(lambda x,y:x&y,items)
你需要创建一个以
set
对象作为处理对象的视图对象,然后就可以使用
&
运算符计算项目的交集。使用
reduce
函数。