π Day 83/150 – Find Common Keys in Dictionaries in Python
Dictionaries are one of Python's most powerful data structures. Sometimes you need to compare two dictionaries and identify the keys they have in common. Python provides several easy and efficient ways to accomplish this.
In this post, we'll explore four different methods to find common keys between dictionaries.
Method 1 – Using Set Intersection (&)
The easiest way is to compare the dictionary keys using the intersection operator.
Output:
{'age', 'city'}
Explanation:
- keys() returns a view of dictionary keys.
- The & operator finds keys present in both dictionaries.
Method 2 – Using intersection() Method
You can also use the intersection() method for better readability.
dict1 = {"a": 1, "b": 2, "c": 3} dict2 = {"b": 5, "c": 7, "d": 9} common = dict1.keys().intersection(dict2.keys()) print(common)
Output:
{'b', 'c'}
Explanation:
- intersection() performs the same operation as &.
- It returns a set of common keys.
Method 3 – Using a For Loop
Loop through one dictionary and check whether each key exists in the other.
ydict1 = {"x": 10, "y": 20, "z": 30} dict2 = {"y": 100, "z": 200, "a": 300} for key in dict1: if key in dict2: print(key)
Output:
z
Explanation:
- Iterate over the first dictionary.
- Print keys that also exist in the second dictionary.
Method 4 – Taking User Input
Compare two user-defined dictionaries.
dict1 = {"apple": 5, "banana": 3, "mango": 7} dict2 = {"banana": 10, "orange": 4, "apple": 2} common = dict1.keys() & dict2.keys() print("Common Keys:", common)
Output:
Common Keys: {'apple', 'banana'}
Explanation:
- Works with any dictionaries.
- Returns only the keys that appear in both.
Comparison of Methods
| Method | Best For |
|---|---|
| Set Intersection (&) | Fastest and shortest |
| intersection() | Readable code |
| For Loop | Learning and custom logic |
| User Dictionary | Real-world dictionary comparison |
π₯ Key Takeaways
✅ Dictionary keys can be compared using set operations.
✅ The & operator is the shortest and fastest way to find common keys.
✅ intersection() offers the same functionality with clearer syntax.
✅ A for loop is useful when additional conditions or processing are required.
✅ Finding common keys is useful in data comparison, configuration matching, and API response validation.


0 Comments:
Post a Comment