Computer Science
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.
Python
Python Dictionaries
11 Likes
Answer
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
Answered By
3 Likes
Related Questions
Can you store the details of 10 students in a dictionary at the same time ? Details include - rollno, name, marks, grade etc. Give example to support your answer.
Given the dictionary x = {'k1':'v1', 'k2':'v2', 'k3':'v3'}, create a dictionary with the opposite mapping, i.e., write a program to create the dictionary as :
inverted_x = {'v1': 'k1' , 'v2' :'k2' , 'v3':'k3'}Write a program that checks if two same values in a dictionary have different keys. That is, for dictionary D1 = { 'a' : 10, 'b': 20, 'c' : 10}, the program should print 2 keys have same values and for dictionary D2 = {'a' : 10, 'b' : 20, 'c' : 30} , the program should print No keys have same values.
Write a program to check if a dictionary is contained in another dictionary e.g., if
d1 = {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15}then d1 is contained in d2.