Joshhh Joshhh - 1 month ago 7
Python Question

python: multiply an input by a number in a dict

I am trying to multiple a user given number, by another part of code inside a pre made dictionary. Here is my example code

randomdict = {'22' : {'name' : 'sponge', 'price' : 1}}
choice = input("Enter a number: ")
amount = input("How much of that item?: ")
if choice in randomdict:
price = amount * (randomdict['price'])
print("Price is "+str(price))


As you can see I'm trying to get the amount the user inputted in, multiplied by the price of the item which is saved in the dict
randomdict
. How do I do this? I have tried time and time again but cannot figure it out

Answer

randomdict['price'] doesn't exist. You want randomdict[choice]['price']

Further, you want your amount to be an integer if you want to calculate the price.

price  = int(amount) * randomdict[choice]['price']

As a side-note: price may not be the greatest name for this value. This value is really a total (price x quantity) not the price. Writing that out explicitly:

quantity = int(amount)
price = randomdict[choice]['price']
total = price * quantity
Comments