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中是否具有相同的键或值有关的问题交给我。

学习愉快!

  1. Python基础教程

相关文章:

  • 2021-11-05
  • 2021-07-27
  • 2021-11-13
  • 2021-06-17
  • 2022-12-23
  • 2021-10-10
  • 2021-04-01
猜你喜欢
  • 2021-08-04
  • 2022-12-23
  • 2022-02-17
  • 2021-12-22
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案