python - 仅删除 Python 字典中的值
问题描述
我试图只删除 Python 字典中的值。
我定义了一个名为 remove_table 的函数,如下所示,希望只删除客户的信息,以便我可以为下一个客户重用 table_number。但是,我的 remove_table 函数也会删除表号
tables = {
1: {'name': 'Jiho','vip_status': False,
'order': {'drinks': 'Orange Juice, Apple Juice',
'food_items': 'Pancakes',
'total': [534.50, 20.0, 5]
} },2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {},}
def assign_table(table_number, name, vip_status=False):
tables[table_number]['name'] = name
tables[table_number]['vip_status'] = vip_status
tables[table_number]['order'] = {}
def remove_table(table_number):
del tables[table_number]
remove_table(1)
print(tables)
{2:{}、3:{}、4:{}、5:{}、6:{}、7:{}}
由于使用表1的客户离开了,我删除了表信息并尝试使用assign_table函数将另一个客户分配到表1,但出现错误。
assign_table(1,'John',True)
回溯(最后一次调用):文件“script.py”,第 43 行,在 assign_table(1,'John',True) 文件“script.py”,第 20 行,在 assign_table 表 [table_number]['name'] = 名称 KeyError: 1
谢谢!!
解决方案
def remove_table(table_number):
tables[table_number] = {}
您可以将值设置为空字典。
推荐阅读
- matlab - Matlab中0和1的时间复杂度和内存复杂度有什么区别吗
- python - 在 sympy 中引发 TypeError("Invalid comparison of non-real %s" % me)
- python - 使用正则表达式从列表中提取部分和子部分
- python - 了解 tkinter 主循环期间的异常处理
- javascript - Daisy 与 div 的其他内容重叠
- apache-kafka - Can we load data into any of the database using kafkastreams
- php - 使用 Laravel 迁移用 HTML 预填充数据库表列字段
- java - 如何执行 java -jar
.jar 在命令提示符下使用 java - c# - 用一个唯一值更新查询,另一个用不同的值更新查询
- java - java.lang.NoSuchMethodError: 'void com.google.common.base.Preconditions.checkArgument(boolean, java.lang.String, java.lang.Object)