Find a common element in the two dictionary objects

There are two dictionary objects, want to find the same elements (the same key and value, key: value).

a = { 'x': 1 , 'y': 2, 'z': 3}, b = { 'w': 10, 'x': 11, 'y': 2}. We can collection (set) inside the operational use.

# 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) }

These types of operations can be used to change the contents of the dictionary or filtration. For example, suppose you want to create a new dictionary, delete the selected key. Here are some sample code uses the dictionary to understand:

# 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}

Guess you like

Origin www.cnblogs.com/jeffrey-yang/p/11283693.html