Intersecting two dictionaries in Python
Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets. Dictionaries are indexed by keys. They are generally optimized to retrieve values when the key is known. Values (definitions) are mapped to a specific key (words) similar to that of a dictionary in the real world.
Now our task is intersecting two dictionaries using their keys. We can achieve this in two ways
- Dictionary Comprehension
- & Operator
Using Dictionary Comprehension:
Before we move on to learn this method, please refer to this article about Dictionary Comprehension for better understanding.
https://docs.google.com/document/d/13bMIsQim-pDQTk2crKPrbxSGlvGKqt_8ZU_UMGo8MqI/edit?usp=sharing (To be replaced with the article link to i2tutorials website)
Now, let’s take an example of two dictionaries x and y with the following keys and values.
We now take an iterator i which is the key of x and check whether the i(key) in x exists in y as well by running a for loop.
{ i : x[i] for i in x if i in y }
If it finds one, the common key and its value are pushed inside a new dictionary named z.
z = { i : x[i] for i in x if i in y }
We can see the common key:value pair {‘a’: ‘one’} has been printed when we tried to print z.
Using &(AND) Operator:
Let’s consider the same example of two dictionaries x and y. We now try to convert the two dictionaries into a list using the items() function and relate them using the &(AND) Operator.
x.items() & y.items()
After this, we use the dict() function to convert the common key-value pairs into a dictionary and store them in z.
z = dict( x.items() & y.items() )