最简单的方法是查找键,值或项的交集,即 &
在两个字典之间使用运算符。
$title(example.py)
a = { 'x' : 1, 'y' : 2, 'z' : 3 }
b = { 'u' : 1, 'v' : 2, 'w' : 3, 'x' : 1, 'y': 2 }
set( a.keys() ) & set( b.keys() ) # Output set(['y', 'x'])
set( a.items() ) & set( b.items() ) # Output set([('y', 2), ('x', 1)])
Set intersection()
方法返回一个集合,其中包含集合a和集合b中都存在的项目。
$title(example.py)
a = { 'x' : 1, 'y' : 2, 'z' : 3 }
b = { 'u' : 1, 'v' : 2, 'w' : 3, 'x' : 1, 'y': 2 }
setA = set( a )
setB = set( b )
setA.intersection( setB )
# 输出
# set(['y', 'x'])
for item in setA.intersection(setB):
print item
# 输出
#x
#y
http://blog.xqlee.com/article/737.html