當前問題:接受輸入以選擇字典鍵,并將quantity鍵:值對添加到該嵌套字典中。
這是我的嘗試
menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99"},
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
selection = int(input("Please select your item:\n"))
if int(selection) < 1 or int(selection) > 6:
print("Invalid selection. Please try again. \n")
count = int(input("Enter quantity: \n"))
# This is the line I'd like help with
menu[selection].update["quantity": count]
如何構造該行menu[selection].update["quantity": count]以便將選單更新為:
menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99", "quantity": 2}, # Note the new k:v here
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
uj5u.com熱心網友回復:
嘗試這個:
# Use 'dict.update()` with inputting a dict with key and value as you like
menu[selection].update({"quantity": count})
輸入運行:
Please select your item:
1
Enter quantity:
2
輸出:
# print(menu)
{1: {'item': 'Green Beret Omelette', 'quantity': 2, 'price': '$12.99'},
2: {'item': 'Get to the Chopped Salad', 'price': '$14.99'},
3: {'item': 'Pump You Up Protein Shake', 'price': '$9.99'},
4: {'item': "I'll Be Baby Back Ribs", 'price': '$22.99'},
5: {'item': 'Let Off Some Steamed Vegetables', 'price': '$4.99'},
6: {'item': 'The Ice Cream Cometh', 'price': '$15.99'}}
uj5u.com熱心網友回復:
OPH(原始問題)在這里。我向杰米尋求幫助,他為我發帖,所以給他所有的支持。
這是一個更新的版本/嘗試。
menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99"},
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
key = int(input("Please select your item:\n"))
if int(key) < 1 or int(key) > 6:
print("Invalid selection. Please try again. \n")
isOrdering = True
continue
quan = int(input("Enter quantity: \n")), menu.update[key]({"quantity": quan})
menu[key]["subTotal"] = menu[key]("quantity") * menu[key]("price")
我目前遇到的錯誤是“發生例外:TypeError 'builtin_function_or_method' object is not subscriptable” :
quan = int(input("輸入數量:\n")), menu.update[key]({"quantity": quan})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528997.html
