How to Find Keys with Matching Values in Two Dictionaries in Python
Find dictionary keys where both dictionaries have the exact same value by iterating over key-value pairs and comparing them.
Python code
16 linesdef find_matching_values(dict1, dict2):
"""Return list of keys that have the same value in both dicts."""
matches = []
for key, value in dict1.items():
if key in dict2 and dict2[key] == value:
matches.append(key)
return matches
if __name__ == "__main__":
# Example usage
dict_a = {"apple": 5, "banana": 3, "cherry": 8, "date": 2}
dict_b = {"apple": 5, "banana": 10, "cherry": 8, "elderberry": 7}
result = find_matching_values(dict_a, dict_b)
print(f"Keys with matching values: {result}")
Output
Keys with matching values: ['apple', 'cherry']
How it works
The function iterates over each key-value pair in the first dictionary using .items(). For each pair, it checks whether the key exists in the second dictionary with key in dict2 and whether the associated values are equal with dict2[key] == value. If both conditions hold, the key is added to the results list. This approach has O(n) time complexity, where n is the number of items in the first dictionary, and keeps the logic clear and readable.
Common mistakes
- Forgetting to check if the key exists in the second dictionary before accessing dict2[key], which raises KeyError.
- Assume values are hashable; if values are lists or dicts, use `==` carefully as it compares by equality not identity.
- Returning a set instead of a list when order matters, as sets are unordered.
Variations
- Use a dictionary comprehension: `{k: dict1[k] for k in dict1 if k in dict2 and dict1[k] == dict2[k]}` to get a dict of matching key-value pairs.
- Use `set(dict1.items()) & set(dict2.items())` to find common key-value tuples, but note this creates sets of tuples and may be slower for large dicts.
Real-world use cases
- Syncing configurations between environments where only unchanged settings should be copied.
- Reconciling inventory records between two systems to detect items that haven't changed.
- Merging user profiles from two sources where only fields that match should be kept.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.