我如何从字典中找到输入的值

时间:2020-08-28 12:45:37

标签: python dictionary

我正在为学校项目编写此代码,如下所示:

valid_entries = ['y', 'n', 'hatchback', 'estate', 'saloon']
model_options = {
    'Hatchback' : 535000,
    'Saloon' : 495000,
    'Estate' : 625000
}
total_price = 0

model_chosen = input("Which car model do you want to buy?\n> ")
while model_chosen not in valid_entries:
    print("Invalid Input\nTry again")
    model_chosen = input("Which car model do you want to buy?\n> ")

有没有办法我可以访问这些值并将其与输入进行比较并将其添加到分数中?

2 个答案:

答案 0 :(得分:0)

值是model_options [model_chosen],您到底要做什么? 你可以做: 总计+ = model_options [model_chosen]。

答案 1 :(得分:0)

您可以使用以下语法访问值:dict [key]。例如,在您的代码中,models_options [Estate]的值为625000。您实际上并不需要列表valid_entries。您可以尝试以下代码:

valid_entries = ['y', 'n', 'hatchback', 'estate', 'saloon']
model_options = {
    'Hatchback' : 535000,
    'Saloon' : 495000,
    'Estate' : 625000
}
total_price = 0

model_chosen = input("Which car model do you want to buy?\n> ")
while model_chosen not in model_options:
    print("Invalid Input\nTry again")
    model_chosen = input("Which car model do you want to buy?\n> ")

total_price+=model_options[model_chosen]

print(total_price)