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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

16 lines
Python 3.9+
def 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

stdout
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

  1. 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.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.