首页 > 解决方案 > 仅删除 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

谢谢!!

标签: python

解决方案


def remove_table(table_number):
    tables[table_number] = {}

您可以将值设置为空字典。


推荐阅读