Python示例,用於查找2個或更多詞典之間的常見項目,即字典相交項目。
1.使用“&”運算符的字典交集
最簡單的方法是查找鍵,值或項的交集,即 & 在兩個字典之間使用運算符。
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)])
2.設置交集()方法
Set intersection()方法返回一個集合,其中包含集合a和集合b中都存在的項。
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 )
# Output set(['y', 'x'])
for item in setA.intersection(setB):
print item
#x
#y
請把與檢查兩個字典在python中是否具有相同的鍵或值有關的問題交給我。
學習愉快!