How to Find Common Keys from Two Dictionaries in Python
Finding the shared keys between two dictionaries is a frequent operation in Python - whether you're merging datasets, comparing configurations, detecting overlapping records, or synchronizing data sources. Python offers several approaches to accomplish this, ranging from simple loops to elegant set operations.
In this guide, you'll learn multiple methods to find common keys between two dictionaries, understand their trade-offs, and choose the best one for your use case.
Understanding the Problem
Given two dictionaries, the goal is to identify all keys that exist in both dictionaries.
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 3, "d": 4, "e": 5, "f": 6}
# Expected common keys: "c", "d"
The values associated with the keys are irrelevant: we only care about whether the key appears in both dictionaries.
Using Set Intersection with .keys() (Recommended)
The most Pythonic and efficient approach leverages the fact that dictionary .keys() returns a set-like view object that supports set operations directly.
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 3, "d": 4, "e": 5, "f": 6}
common_keys = dict_a.keys() & dict_b.keys()
print(common_keys)
Output:
{'c', 'd'}
How it works:
dict_a.keys()returns a view of all keys indict_a.- The
&operator performs a set intersection between the two key views. - The result is a set containing only keys present in both dictionaries.
Dictionary key views natively support set operations (&, |, -, ^) without requiring explicit conversion to sets. This is both memory-efficient and runs in O(min(m, n)) average time, where m and n are the sizes of the dictionaries.
You can also use the .intersection() method explicitly:
common_keys = dict_a.keys() & dict_b.keys()
# Equivalent to:
common_keys = set(dict_a).intersection(dict_b)
Using a Dictionary Comprehension
If you need not just the common keys but also their values from one of the dictionaries, a dictionary comprehension is ideal:
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 30, "d": 40, "e": 50, "f": 60}
# Common keys with values from dict_a
common = {key: dict_a[key] for key in dict_a if key in dict_b}
print(common)
Output:
{'c': 3, 'd': 4}
This approach runs in O(m) time (where m is the size of dict_a) since key in dict_b is an O(1) dictionary lookup.
Using a for Loop with in Operator
A straightforward loop approach is the most explicit and easiest to understand, making it a good choice when readability is the priority or when you need extra processing logic:
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 3, "d": 4, "e": 5, "f": 6}
common_keys = []
for key in dict_a:
if key in dict_b:
common_keys.append(key)
print(common_keys)
Output:
['c', 'd']
How it works:
- The loop iterates over every key in
dict_a. key in dict_bchecks if that key exists indict_b- this is an O(1) operation for dictionaries.- Matching keys are collected in a list.
Time complexity: O(m), where m is the number of keys in dict_a.
Using filter() with a Lambda Function
For a functional programming style, filter() provides a compact alternative:
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 3, "d": 4, "e": 5, "f": 6}
common_keys = list(filter(lambda key: key in dict_b, dict_a))
print(common_keys)
Output:
['c', 'd']
The lambda checks each key from dict_a against dict_b, and filter() keeps only the matches.
Common Mistake: Using .items() Intersection When Only Keys Matter
A frequent error is using the & operator on .items() instead of .keys(). This compares both keys and values, which means keys with different values won't be considered "common."
Incorrect approach (when you only want common keys)
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 30, "d": 40, "e": 5, "f": 6}
# This checks if BOTH the key AND value match
common = dict_a.items() & dict_b.items()
print(common)
Output:
set()
No results! Even though keys "c" and "d" exist in both dictionaries, their values differ (3 vs 30, 4 vs 40), so .items() intersection finds nothing.
Correct approach: use .keys()
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 30, "d": 40, "e": 5, "f": 6}
common = dict_a.keys() & dict_b.keys()
print(common)
Output:
{'c', 'd'}
.items() & vs .keys() &dict_a.keys() & dict_b.keys()→ finds keys present in both dictionaries (ignores values).dict_a.items() & dict_b.items()→ finds key-value pairs that are identical in both dictionaries.
Choose based on whether values should factor into the comparison.
Comparing Values for Common Keys
Once you've identified the common keys, you might want to compare or merge their values:
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 30, "d": 4, "e": 5, "f": 6}
common_keys = dict_a.keys() & dict_b.keys()
# Show values from both dictionaries for common keys
for key in sorted(common_keys):
match = "✅ same" if dict_a[key] == dict_b[key] else "❌ different"
print(f" Key '{key}': dict_a={dict_a[key]}, dict_b={dict_b[key]} ({match})")
Output:
Key 'c': dict_a=3, dict_b=30 (❌ different)
Key 'd': dict_a=4, dict_b=4 (✅ same)
Creating a Reusable Function
For production code, a reusable function keeps things clean and testable:
def find_common_keys(*dicts: dict) -> set:
"""Find keys common to all provided dictionaries.
Args:
*dicts: Two or more dictionaries to compare.
Returns:
A set of keys present in every dictionary.
Raises:
ValueError: If fewer than two dictionaries are provided.
"""
if len(dicts) < 2:
raise ValueError("At least two dictionaries are required.")
common = set(dicts[0].keys())
for d in dicts[1:]:
common &= d.keys()
return common
# Compare two dictionaries
dict_a = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_b = {"c": 3, "d": 4, "e": 5, "f": 6}
print(find_common_keys(dict_a, dict_b))
# Compare three dictionaries
dict_c = {"c": 10, "f": 20, "g": 30}
print(find_common_keys(dict_a, dict_b, dict_c))
Output:
{'c', 'd'}
{'c'}
This function scales to any number of dictionaries, progressively intersecting keys across all inputs.
Quick Comparison of Methods
| Method | Time Complexity | Returns | Best For |
|---|---|---|---|
.keys() & (set intersection) | O(min(m, n)) | set | Most use cases (recommended) |
| Dictionary comprehension | O(m) | dict | When you need keys + values |
for loop with in | O(m) | list | Extra processing during iteration |
filter() with lambda | O(m) | list | Functional programming style |
.items() & | O(min(m, n)) | set of tuples | Matching key-value pairs exactly |
m and n are the sizes of the two dictionaries.
Conclusion
Python provides several efficient ways to find common keys between two dictionaries:
.keys() &(set intersection) is the most Pythonic and efficient approach - use it as your default.- Dictionary comprehension is ideal when you also need the associated values.
- A
forloop gives maximum flexibility for adding custom logic during the comparison. .items() &should only be used when you need both keys and values to match.
For comparing more than two dictionaries, progressively intersect the key sets using a loop. All key-based approaches benefit from Python's O(1) average-time dictionary lookups, making them efficient even with large datasets.