Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Intersect two dictionaries through keys
In Python, intersecting two dictionaries through keys means creating a new dictionary containing only the keys that exist in both dictionaries. This is useful for finding common data between two datasets.
Input:
dict_1 = {'A': 1, 'B': 2, 'C': 3}
dict_2 = {'A': 1, 'C': 4, 'D': 5}
Output:
{'A': 1, 'C': 3}
Using Dictionary Comprehension
Dictionary comprehension provides the most readable approach to intersect dictionaries by keys ?
# 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)
{'A': 1, 'C': 3}
This method keeps values from the first dictionary (dict_1) for all common keys.
Using Set Intersection with Keys
You can use set operations to find common keys, then build the result dictionary ?
# initializing the dictionaries
dict_1 = {'A': 1, 'B': 2, 'C': 3}
dict_2 = {'A': 1, 'C': 4, 'D': 5}
# finding common keys using set intersection
common_keys = dict_1.keys() & dict_2.keys()
result = {key: dict_1[key] for key in common_keys}
# printing the result
print(result)
{'A': 1, 'C': 3}
Using Bitwise AND on Items
The bitwise AND operator on dictionary items filters key-value pairs that are identical in both dictionaries ?
# initializing the dictionaries
dict_1 = {'A': 1, 'B': 2, 'C': 3}
dict_2 = {'A': 1, 'C': 4, 'D': 5}
# finding identical key-value pairs
result = dict(dict_1.items() & dict_2.items())
# printing the result
print(result)
{'A': 1}
Note: This method only includes keys where both the key AND value are identical in both dictionaries. Key 'C' is excluded because it has different values (3 vs 4).
Comparison
| Method | Behavior | Use Case |
|---|---|---|
| Dictionary Comprehension | Common keys, values from first dict | General key intersection |
| Set Intersection | Common keys, values from first dict | When you need the key set first |
| Bitwise AND | Identical key-value pairs only | Exact match requirements |
Conclusion
Use dictionary comprehension for general key intersection. Use bitwise AND on items when you need identical key-value pairs. Both methods are efficient for intersecting dictionaries based on your specific requirements.
