我正在使用python建立基本商店,其中包含商品及其价格的字典。我正在为购物车使用字典,希望用户能够向购物车中添加项目。为此,我旨在将键和值从产品字典复制到购物车字典。我该怎么办?
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5, "Whiteboard": 30}
cart = {}
def addToCart():
productToAdd = input("What would you like to add? ")
for k,v in products.items():
if productToAdd == k:
price = v
cart[productToAdd] = cart[v]
break
答案 0 :(得分:2)
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5, "Whiteboard": 30}
cart = {}
def addToCart():
try:
productToAdd = input("What would you like to add? ")
cart[productToAdd]=products[productToAdd]
except KeyError:
print("No such product")
请注意,python区分大小写,“ pencil”和“ Pencil”不同。 如果您确定产品首先要成为大写字母,则可以使用
productToAdd = input("What would you like to add? ").title()
答案 1 :(得分:0)
您可以使用dict.setdefault(key, default=None)
示例:
def addToCart():
productToAdd = input("What would you like to add? ")
cart[productToAdd]=products.setdefault(productToAdd, 'No such product')
答案 2 :(得分:0)
假设用户将从列表中选择项目(尤其是从键中选择),则:
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5,
"Whiteboard": 30}
cart = {}
def addToCart():
productToAdd = input("What would you like to add? ")
if not productToAdd.title() in products: # for removing caps confusion
print('No such item')
else: cart[productToAdd] = products[productToAdd]
>>> addToCart()
What would you like to add? Pencil
>>> cart
{'Pencil': 1}
答案 3 :(得分:-1)
我不得不使用raw_input,否则它将无法接受“ Pencil”之类的字符串。 这就是复制键值对的方式。
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5, "Whiteboard": 30}
cart = {}
def addToCart():
productToAdd = raw_input("What would you like to add? ")
for k,v in products.items():
print(k)
if productToAdd == k:
cart[k] = v
break
addToCart()
print(cart)