如何从字典内的列表中删除元素?

时间:2018-10-24 22:30:24

标签: python

days = {'10/02':['Eat Pie', 'Eat Pizza'], '12/03': 'Drink Wine'}

def delete_event(k, x, y):
  if type(days[k]) == list:
    for k in days:
  days[k] = days[k][x:y]
  elif type(days[k]) != list:
    del days[k]
  print('That event has been deleted. Here is the new list: ')
  print(days)

我有一本包含日期和事件的字典。日期可以列表的形式保存多个事件。我将如何从列表中删除特定事件?但是,如果事件不止一个,则删除整个事件(键和值)。有可能做到吗?我需要具有算法的功能。每当我输入x和y的值时,它就会摆脱所有键中的值,而不仅仅是我想要的特定键。 https://repl.it/@footballmania1/Mock 那是我当前项目的链接,我需要帮助修复删除功能。

3 个答案:

答案 0 :(得分:0)

def remove_schedule(days, date, to_remove=None):
    if to_remove is None:
        del days[date]
    else:
        days[date].remove(to_remove)

days = {'10/02': ['Eat Pie', 'Eat Pizza'], '12/03': ['Drink Wine']}
remove_schedule(days, '10/02', 'Eat Pizza')
print(days)

这是密码。

上面这些代码的结果将是

{'10/02': ['Eat Pie'], '12/03': ['Drink Wine']}

如果您想删除整个字典键,只需执行

remove_schedule(days, '10/02')

这将删除键和值

答案 1 :(得分:0)

使用此功能:

def deleter(my_dict, date, event):
    try:
        my_dict[date].remove(event)
        if not my_dict[date]:
            my_dict.pop(date)
    except:
        del my_dict[date]

它接受您的字典,日期和事件

例如

days = {'10/02':['Eat Pie', 'Eat Pizza'], '12/03': 'Drink Wine'}
deleter(days, '12/03', 'Drink Wine')
deleter(days, '10/02', 'Eat Pie')

print(days)
>> {'10/02': ['Eat Pizza']}

答案 2 :(得分:-1)

尝试一下:

days = {'10/02':['Eat Pie', 'Eat Pizza'], '12/03': ['Drink Wine']}
for i in days.values():
    del i[0]
print (days)