w3resource

Python: Match key values in two dictionaries


38. Match Key Values in Two Dictionaries

Write a Python program to match key values in two dictionaries.

Visual Presentation:

Python Dictionary: Match key values in two dictionaries.

Sample Solution:

Python Code:

# Create two dictionaries 'x' and 'y' with key-value pairs.
x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
	
# Use set operations to find the common key-value pairs between 'x' and 'y'.
# Iterate through the common key-value pairs using a for loop.
for (key, value) in set(x.items()) & set(y.items()):
    # Print a message indicating that the key and value are present in both 'x' and 'y'.
    print('%s: %s is present in both x and y' % (key, value))

Sample Output:

key1: 1 is present in both x and y 

For more Practice: Solve these Related Problems:

  • Write a Python program to compare two dictionaries and print the keys whose values match in both.
  • Write a Python program to iterate over keys in one dictionary and check if the corresponding value in another dictionary is the same.
  • Write a Python program to use set intersection on the keys of two dictionaries and then verify matching values for each intersected key.
  • Write a Python program to implement a function that finds all keys present in both dictionaries where the values are equal, and print them with their common value.

Python Code Editor:

Previous: Write a Python program to replace dictionary values with their sum.
Next: Write a Python program to store a given dictionary in a json file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.