Informatics Practices
Write a Python program that accepts a value and checks whether the inputted value is part of the given dictionary or not. If it is present, check for the frequency of its occurrence and print the corresponding key, otherwise print an error message.
Python Dictionaries
3 Likes
Answer
d = {
'A': 'apple',
'B': 'banana',
'C': 'apple',
'D': 'orange',
'E': 'strawberry'
}
v = input("Enter a value to check: ")
k = []
for key, value in d.items():
if value == v:
k.append(key)
if len(k) > 0:
print("The value", v, "is present in the dictionary.")
print("It occurs", len(k), "time(s) and is associated with the following key(s):", k)
else:
print("The value", v, "is not present in the dictionary.")
Output
Enter a value to check: apple
The value apple is present in the dictionary.
It occurs 2 time(s) and is associated with the following key(s): ['A', 'C']
Answered By
1 Like
Related Questions
Write the output of the following code:
d = {'a':1, 'b':2, 'c':3} print (d['a'])
Write a program to input your friends' names and their phone numbers and store them in a dictionary as the key-value pair. Perform the following operations on the dictionary:
(a) Display the Name and Phone numbers of all your friends.
(b) Add a new key-value pair in this dictionary and display the modified dictionary.
(c) Delete a particular friend from the dictionary.
(d) Modify the phone number of an existing friend.
(e) Check if a friend is present in the dictionary or not.
(f) Display the dictionary in sorted order of names.
Consider the following dictionary Prod_Price.
Prod_Price = {'LCD' : 25000, 'Laptop' : 35000, 'Home Theatre' : 80000, 'Microwave Oven' : 18000, 'Electric Iron' : 2800, 'Speaker' : 55000}
Find the output of the following statements:
(a) print(Prod_Price.get('Laptop'))
(b) print(Prod_Price.keys())
(c) print(Prod_Price.values())
(d) print(Prod_Price.items())
(e) print(len(Prod_Price))
(f) print('Speaker' in Prod_Price)
(g) print(Prod_Price.get('LCD'))
(h) del ProdPrice['Home Theatre'] print (ProdPrice)
Write a program that prompts the user for product names and prices, and store these key-value pairs in a dictionary where names are the keys and prices are the values. Also, write a code to search for a product in a dictionary and display its price. If the product is not there in the dictionary, then display the relevant message.