在python中将dict键与用户输入匹配

2024-09-28 19:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个python比萨饼应用程序(是的,我知道有很多),但是,我遇到了一个需要帮助理解的场景

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)

我知道这段代码在if order1部分不起作用。然而,我感兴趣的是了解如何获取输入并将其与dict pizzaSize的键相匹配

这就是为什么我要这么做。我想获取用户输入并检查它是否包含在pizzaSizedict中

如果字符串包含在那里,我想添加与顶部的price变量集匹配的键的值。谢谢大家!


Tags: 应用程序if场景pricesmallmediumlargeprint
2条回答

您可以通过多种方式完成:

  1. 使用iforder1 in pizzaSize,如果为true,则添加价格
  2. 使用.get()查看字典中是否存在该大小,并做出相应的反应
  3. 使用pizzaSize[order1]并在dict中不存在键时捕获异常

您可能需要使用.get()从dict获取相应的值,如果它不存在,您将使用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)

相关问题 更多 >