- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Intersect two dictionaries through keys
In this article, we are going to learn how to intersect two dictionaries using keys. We have to create a new dictionary with common keys. Let's see an example.
Input: dict_1 = {'A': 1, 'B': 2, 'C': 3} dict_2 = {'A': 1, 'C': 4, 'D': 5} Output: {'A': 1, 'C': 3}
We are going to use the dictionary comprehension to solve the problem. Follow the below steps to write the code.
- Initialize dictionaries.
- Iterate over the dictionary one and add elements that are not in dictionary two.
- Print the result.
Example
# initializing the dictionaries dict_1 = {'A': 1, 'B': 2, 'C': 3} dict_2 = {'A': 1, 'C': 4, 'D': 5} # finding the common keys result = {key: dict_1[key] for key in dict_1 if key in dict_2} # printing the result print(result)
If you run the above code, then you will get the following result.
Output
{'A': 1, 'C': 3}
We can also solve the problem using bitwise & operator. It simply filters the common keys and corresponding value from the dictionaries. Only filters keys with the same value.
Example
# initializing the dictionaries dict_1 = {'A': 1, 'B': 2, 'C': 3} dict_2 = {'A': 1, 'C': 4, 'D': 5} # finding the common keys result = dict(dict_1.items() & dict_2.items()) # printing the result print(result)
If you run the above code, then you will get the following result.
Output
{'A': 1}
Conclusion
You can choose any method you want based on your preference and use case. If you have any queries, mention them in the comment section.
Advertisements