-3

I am creating a python pizza app (yes I know there is a ton of them) but, I am coming across a scenario that I need help understanding.

price = 0

toppings = {
    'mushrooms': .5,
    'onions': .5,
    'pepperoni': 1,
    'extra-cheese':1
}

pizzaSize = {
    'small': 8,
    'medium': 10,
    'large': 12,
    'x-large': 14
}


order1 = input("Welcome to the pizza store what size pizza can we get for you (small, medium, large, or x-large): " )

print(order1)

if order1 == pizzaSize.keys():
    print(order1)

I understand that this code will not work when it comes to the if order1 part. However, I am interested in understanding how I could take the input and match it with a key of the dict pizzaSize.

Here is why I want to do that. I want to take user input and check and see if it is contained inside the pizzaSize dict.

If the string is contained there, I want to add the value of that key that matched to the price variable set at the top. Thank you all!

azro
  • 53,056
  • 7
  • 34
  • 70
aroe
  • 147
  • 2
  • 13

2 Answers2

1

You can do it multiple ways:

  1. Use if order1 in pizzaSize, if it is true, add the price
  2. Use .get() to see if the size is present in the dictionary and react accordingly.
  3. Use pizzaSize[order1] and catch the exception if the key is not present in dict.
Anirudh Bagri
  • 2,346
  • 1
  • 21
  • 33
0

You need may use an .get() to get the corresponding value from the dict, if it doesn't exist you'll a None

order1 = input("Welcome to the pizza store what size pizza can we get for you (small, medium, large, or x-large): " )

size_price = pizzaSize.get(order1)
if size_price is not None:
    price += size_price
else:
    print(f"Sorry the size '{order1}' doesn't exist")
    exit(1)
Booboo
  • 38,656
  • 3
  • 37
  • 60
azro
  • 53,056
  • 7
  • 34
  • 70
  • File "pizzaAppv2.py", line 21, in sizePrice = pizzaSize.get(pizzaSize) TypeError: unhashable type: 'dict' that is the error you get if you do it like you said – aroe Aug 16 '20 at 14:40
  • @aroe there was a mistake, look again the new code – azro Aug 16 '20 at 14:41
  • That's a good point but I don't think it matters. Either way it's just adding the new price to the price var. However it is erroring now see above ^. – aroe Aug 16 '20 at 14:43
  • fixed, I passed it the new var of order1 and it output the correct price. – aroe Aug 16 '20 at 14:44
  • Very sorry @azro for not accepting your answer! Just did it now and it was very useful thank you so much! – aroe Aug 19 '20 at 20:28