如何在Python中更新嵌套字典:添加quantity键值对
问题:为选中的菜单条目添加quantity键值对
通过输入选择字典的键,为对应的嵌套字典添加一个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更新为包含选中条目quantity键值对的形式。
修改方案
问题出在update方法的调用方式上,Python字典的update()是方法,需传入字典参数并通过括号调用,而非方括号。有两种简洁的修改方式:
- 直接赋值(最推荐)
直接通过键访问嵌套字典,为quantity键赋值:
menu[selection]["quantity"] = count
- 正确使用
update()方法
若要使用update,需传入包含目标键值对的字典,并用括号调用方法:
menu[selection].update({"quantity": count})
优化后的完整代码
原代码存在输入无效时仍会执行后续操作的问题,可能引发KeyError,这里调整验证逻辑:
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 1 <= selection <= 6: count = int(input("Enter quantity: \n")) # 使用直接赋值方式添加quantity menu[selection]["quantity"] = count else: print("Invalid selection. Please try again. \n") # 打印验证结果 print(menu)
执行后选中条目会新增quantity键值对,符合预期格式。
内容的提问来源于stack exchange,提问作者Jamie.Sgro
相关产品推荐
相关产品推荐

