Matching Key Values in Dictionaries

Write a Python function that takes two dictionaries as input. The function should return a dictionary that contains only the key-value pairs that exist in both input dictionaries.

Example 1:

Input: {"a": 1, "b": 2, "c": 3}, {"a": 1, "b": 2, "d": 4} 
Output: {"a": 1, "b": 2}

Example 2:

Input: {"x": 10, "y": 20, "z": 30}, {"x": 10, "y": 30, "w": 40} 
Output: {"x": 10}

Use a dictionary comprehension to iterate over the key-value pairs in the first dictionary and check if they exist in the second dictionary.

def match_keys(dict1, dict2):
return {k: v for k, v in dict1.items() if k in dict2 and dict2[k] == v}

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!