💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Python 字典交集 – 比较两个字典 > 原文: [https://howtodoinjava.com/python/dictionary-intersection/](https://howtodoinjava.com/python/dictionary-intersection/) Python 示例,用于查找 2 个或更多词典之间的常见项目,即字典相交项目。 ## 1.使用“`&`”运算符的字典交集 最简单的方法是查找键,值或项的交集,即使用两个字典之间的 `&` 运算符。 ```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()`方法 `Set.intersection()`方法返回一个集合,该集合包含集合`a`和集合`b`中都存在的项。 ```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 # Output #x #y ``` 请问有关**检查两个字典在 python 中是否具有相同的键或值**的问题。 学习愉快!