python - 如何获取 dict 中键的值并检查用户控制的字典中的现有值?
问题描述
我有两本字典,一本包含带有价格的项目菜单,另一本用作购物车。
购物车允许玩家在准备结账之前将他们的物品存放在那里以及他们想要的数量。如果玩家希望添加更多相同类型的,我希望程序能够检查它是否已经存在,并能够将现有值和新值一起添加。
最后,当用户准备结账时,我希望能够获取第一个字典的值并将其乘以用户提供的项目数量。
下面是我如何在脑海中计划代码的示例,显然它不是正确的代码,但它应该让我知道我想在这里实现什么。
菜单字典显示商品名称+价格,shopping_cart 显示商品名称+金额
menu = {'litago': 25,
'sandwich': 40,
'cola': 30,
'fruit': 15,
}
shopping_cart = {'cola', 1}
def AddItem():
item_input = input("What would you like to add?".lower() # Cola
item_amount = int(input("How many would you like to add?") # 1
if item_input in shopping_cart:
existing_amount = grab value of cola in shopping cart here
item_amount = item_amount + existing_amount
else:
shopping_cart[item_input] = item_amount
def Checkout():
for every unique item in the shopping cart:
multiply amount per unique item with corresponding price in the menu
我已经进行了检查以确保用户输入对应于菜单上已经存在的项目,如果该项目不存在,它将发出错误。
解决方案
在 python 中,您访问字典中的项目的方式与设置它的方式相同。因此,如果您想查看购物车中可乐的数量,您可以使用shopping_cart['cola']
. 或更一般地说existing_amount = shopping_cart[item_input]
希望你的 Python 学习之旅很棒!
推荐阅读
- php - 如何访问连接表的列
- windows - Windows Batch - 如何修改文件并仅保留以“ ”开头的子字符串?
- java - H2 数据库关于有效 mysql 查询的 sql 语法错误的投诉
- reporting-services - 在 SSRS 中添加组总计
- javascript - 如何使用时间来确定函数是否应该运行?
- c# - C#中如何实现引用返回?
- cakephp - 删除相关行时将外部列设置为 NULL
- javascript - 向上滚动 10 px 到特定的 div
- powerbi - 从 CSV 文件中的单元格值中获取子字符串的存在计数 - Power BI Desktop
- asp.net - 使用 Bit Framework 访问 IApplicationBuilder