Python Program to Find Common Keys in Two Dictionaries
common_keys = dict1.keys() & dict2.keys(), which returns a set of keys present in both dictionaries.Examples
How to Think About It
Algorithm
Code
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 4, 'c': 5, 'd': 6}
common_keys = dict1.keys() & dict2.keys()
print(common_keys)Dry Run
Let's trace the example dict1 = {'a': 1, 'b': 2, 'c': 3} and dict2 = {'b': 4, 'c': 5, 'd': 6} through the code
Get keys of dict1
dict1.keys() = {'a', 'b', 'c'}
Get keys of dict2
dict2.keys() = {'b', 'c', 'd'}
Find intersection
{'a', 'b', 'c'} & {'b', 'c', 'd'} = {'b', 'c'}
Print result
Output: {'b', 'c'}
| Step | dict1.keys() | dict2.keys() | Intersection |
|---|---|---|---|
| 1 | {'a', 'b', 'c'} | ||
| 2 | {'b', 'c', 'd'} | ||
| 3 | {'b', 'c'} |
Why This Works
Step 1: Keys behave like sets
Dictionary keys can be treated like sets, so you can use set operations like intersection with &.
Step 2: Intersection finds common elements
Using dict1.keys() & dict2.keys() finds keys that exist in both dictionaries.
Step 3: Result is a set of common keys
The result is a set containing all keys found in both dictionaries, which you can use or convert as needed.
Alternative Approaches
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
common_keys = set(dict1.keys()).intersection(dict2.keys())
print(common_keys)dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
common_keys = [key for key in dict1 if key in dict2]
print(common_keys)Complexity: O(n) time, O(k) space
Time Complexity
Finding keys and intersecting sets takes time proportional to the number of keys in the smaller dictionary, so O(n).
Space Complexity
The space needed is for the set of common keys, which is at most the size of the smaller dictionary's keys, O(k).
Which Approach is Fastest?
Using & or .intersection() is fastest and most readable; list comprehension is slower due to repeated membership checks.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set intersection (&) | O(n) | O(k) | Fast and clean for large dictionaries |
| Set.intersection() method | O(n) | O(k) | Clear method call, same speed as & |
| List comprehension | O(n*m) | O(k) | Simple for beginners, slower for large dicts |
dict1.keys() & dict2.keys() for a clean and fast way to find common keys.