查找两个字典对象中公共元素

有两个字典对象,想要找出相同的元素(相同的键和值, key: value)。

a = {'x': 1, 'y': 2, 'z': 3},b = {'w': 10, 'x': 11, 'y': 2}。我们可以使用集合(set)里面的操作。

# Find keys in common
a.keys() & b.keys()  # {'x', 'y'}

# Find keys in a that are not in b
a.keys() - b.keys() # {'z'}

# Find (key, value) pairs in common
a.items() & b.items() # { ('y', 2) }

这些类型的操作也可用于更改或过滤字典内容。 例如,假设想要创建一个新字典,同时删除选定键。 以下是使用字典理解的一些示例代码:

# Make a new dictionary with certain keys removed
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
# c is {'x': 1, 'y': 2}

猜你喜欢

转载自www.cnblogs.com/jeffrey-yang/p/11283693.html