Match key values in two dictionaries


The program compares two dictionaries, A and B, and finds common keys and values present in both dictionaries. The program uses the & operator to find the intersection of two sets, which is created using the items() method of the dictionaries. The items() method returns a list of the dictionary's (key, value) pairs as tuples. The set() function is used to convert these lists of tuples into sets.

The for loop iterates over the set intersection and prints each key-value pair that is present in both dictionaries. The output of the program will be the common keys and values that are present in both dictionaries A and B.

Source Code

A = {'Tamil': 92, 'English': 56, 'Maths': 88, 'Sceince': 97, 'Social': 89}
B= {'Tamil': 78, 'English': 68, 'Maths': 88, 'Sceince': 97, 'Social': 56}
for (key, value) in set(A.items()) & set(B.items()):
    print('%s: %s is present in both A and B' % (key, value))

Output

Sceince: 97 is present in both A and B
Maths: 88 is present in both A and B