KnowledgeBoat Logo
|
LoginJOIN NOW

Informatics Practices

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.

Python Dictionaries

3 Likes

Answer

prodDict = {}

n = int(input("Enter the number of products: "))

for i in range(n):
    name = input("Enter the name of product: ")
    price = float(input("Enter the price: "))
    prodDict[name] = price

print(prodDict)

pName = input("\nEnter product name to search: ")

if pName in prodDict:
    print("The price of", pName, "is: ", prodDict[pName])
else:
    print("Product", pName, " not found.")

Output

Enter the number of products: 4
Enter the name of product: Television
Enter the price: 20000
Enter the name of product: Computer
Enter the price: 30000
Enter the name of product: Mobile
Enter the price: 50000
Enter the name of product: Air-Cooler
Enter the price: 35000
{'Television': 20000.0, 'Computer': 30000.0, 'Mobile': 50000.0, 'Air-Cooler': 35000.0}

Enter product name to search: Mobile
The price of Mobile is:  50000.0

Answered By

1 Like


Related Questions