Python | Intersect two dictionaries through keys
Given two dictionaries, the task is to find the intersection of these two dictionaries through keys. Let’s see different ways to do this task.
Method #1: Using dict comprehension
# Python code to demonstrate # intersection of two dictionaries # using dict comprehension # inititialising dictionary ini_dict1 = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} ini_dict2 = {'akshat' :15, 'nikhil' : 1, 'me' : 56} # printing initial json print ("initial 1st dictionary", ini_dict1) print ("initial 2nd dictionary", ini_dict2) # intersecting two dictionaries final_dict = {x:ini_dict1[x] for x in ini_dict1 if x in ini_dict2} # printing final result print ("final dictionary", str(final_dict)) |
initial 1st dictionary {‘vashu’: 5, ‘manjeet’: 10, ‘nikhil’: 1, ‘akshat’: 15}
initial 2nd dictionary {‘nikhil’: 1, ‘me’: 56, ‘akshat’: 15}
final dictionary {‘nikhil’: 1, ‘akshat’: 15}
Method #2: Using & operator
# Python code to demonstrate # intersection of two dictionaries # using dict comprehension # inititialising dictionary ini_dict1 = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} ini_dict2 = {'akshat' :15, 'nikhil' : 1, 'me' : 56} # printing initial json print ("initial 1st dictionary", ini_dict1) print ("initial 2nd dictionary", ini_dict2) # intersecting two dictionaries final_dict = dict(ini_dict1.items() & ini_dict2.items()) # printing final result print ("final dictionary", str(final_dict)) |
initial 1st dictionary {‘vashu’: 5, ‘manjeet’: 10, ‘nikhil’: 1, ‘akshat’: 15}
initial 2nd dictionary {‘nikhil’: 1, ‘akshat’: 15, ‘me’: 56}
final dictionary {‘nikhil’: 1, ‘akshat’: 15}
Recommended Posts:
- Python | Difference in keys of two dictionaries
- Handling missing keys in Python dictionaries
- Python | Sum list of dictionaries with same key
- Python | Merging two Dictionaries
- Python | Subtraction of dictionaries
- Get() method for dictionaries in Python
- Python | Segregating key's value in list of dictionaries
- Python | Get values of particular key in list of dictionaries
- Python | Combine the values of two dictionaries having same key
- Python | Set Difference in list of dictionaries
- Python | Merging two list of dictionaries
- Python | Flatten given list of dictionaries
- Python | Common items among dictionaries
- Python | Sort given list of dictionaries by date
- Python | Removing dictionary from list of dictionaries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



