Computer Science
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.
Python
Python Dictionaries
9 Likes
Answer
d1 = eval(input("Enter a dictionary d1: "))
d2 = eval(input("Enter a dictionary d2: "))
print("d1 =", d1)
print("d2 =", d2)
if len(d1) > len(d2):
longDict = d1
shortDict = d2
else:
longDict = d2
shortDict = d1
for key in shortDict:
if key in longDict:
if longDict[key] != shortDict[key]:
print("d1 and d2 are different ")
break
else:
print("d1 and d2 are different ")
break
else:
print(shortDict, "is contained in", longDict)
Output
Enter a dictionary d1: {1:11, 2:12}
Enter a dictionary d2: {1:11, 2:12, 3:13, 4:15}
d1 = {1: 11, 2: 12}
d2 = {1: 11, 2: 12, 3: 13, 4: 15}
{1: 11, 2: 12} is contained in {1: 11, 2: 12, 3: 13, 4: 15}
Answered By
5 Likes
Related Questions
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'}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.
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.
A dictionary D1 has values in the form of lists of numbers. Write a program to create a new dictionary D2 having same keys as D1 but values as the sum of the list elements e.g.,
D1 = {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
then
D2 is {'A' :6, 'B' : 15}