CBSE Class 11 Computer Science Question 109 of 112

Dictionaries — Question 9

Back to all questions
9
Question

Question 9

Given two dictionaries say D1 and D2. Write a program that lists the overlapping keys of the two dictionaries, i.e., if a key of D1 is also a key of D2, then list it.

Solution
d1 = eval(input("Enter first dictionary: "))
d2 = eval(input("Enter second dictionary: "))

print("First dictionary: ", d1)
print("Second dictionary: ", d2)

if len(d1) > len(d2):
    longDict = d1
    shortDict = d2
else:
    longDict = d2
    shortDict = d1

print("overlapping keys in the two dictionaries are:", end=' ')
for i in shortDict:
    if i in longDict:
        print(i, end=' ')
Output
Enter first dictionary: {'a': 1, 'b':2, 'c': 3, 'd': 4}
Enter second dictionary: {'c': 3, 'd': 4, 'e': 5}
First dictionary:  {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Second dictionary:  {'c': 3, 'd': 4, 'e': 5}
overlapping keys in the two dictionaries are: c d
Answer