Home  >  Article  >  Backend Development  >  Python implements a method to find the same points in two dictionaries (code attached)

Python implements a method to find the same points in two dictionaries (code attached)

不言
不言forward
2018-10-11 14:33:353518browse

What this article brings to you is about the method of finding similarities in two dictionaries in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Requirements

Now there are two dictionaries, and we want to find out the possible similarities between them (same keys, same values)

2. Solution

You only need to use the keys() or item() method to perform common set operations (union, intersection, difference).

a={
    'x':1,
    'y':2,
    'z':3
}
b={
    'w':10,
    'x':11,
    'y':2
}
#找出 在两个字典中读存在的键
print(a.keys() & b.keys())
#找出 存在a却不存在b的键
print(a.keys() -b.keys())
#找出两个字典中,键和值都同时相等的数据
print(a.items() & b.items())

Running results:

values() in the
{'y', 'x'}
{'z'}
{('y', 2)}
dictionary does not support the above set operation, because the same value in the dictionary may correspond to multiple keys.

The above is the detailed content of Python implements a method to find the same points in two dictionaries (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete