Computer Science
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.
Answer
D1 = eval(input("Enter a dictionary D1: "))
print("D1 =", D1)
val = tuple(D1.values())
seen = []
flag = True
for i in val:
if i not in seen:
seen.append(i)
count = val.count(i)
if count > 1:
print(count, "keys have same value of", i)
flag = False
if flag:
print("No keys have same values")Output
Enter a dictionary D1: {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e': 10, 'f': 20}
D1 = {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e': 10, 'f': 20}
3 keys have same value of 10
2 keys have same value of 20
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 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.
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}