Python|从字典列表中删除字典
删除与字典列表中特定键对应的字典的通用实用程序也是一个问题,其简洁版本总是有帮助的。由于引入了主要用于键值对的 No-SQL 数据库,这在 Web 开发中得到了应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 del + 循环
在执行此特定任务的简单方法中,如果特定键与需要删除的键匹配,我们需要使用del删除它。
# Python3 code to demonstrate
# to delete dictionary in list
# using del + loop
# initializing list of dictionaries
test_list = [{"id" : 1, "data" : "HappY"},
{"id" : 2, "data" : "BirthDaY"},
{"id" : 3, "data" : "Rash"}]
# printing original list
print ("The original list is : " + str(test_list))
# using del + loop
# to delete dictionary in list
for i in range(len(test_list)):
if test_list[i]['id'] == 2:
del test_list[i]
break
# printing result
print ("List after deletion of dictionary : " + str(test_list))
The original list is : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 2, ‘data’: ‘BirthDaY’}, {‘id’: 3, ‘data’: ‘Rash’}]
List after deletion of dictionary : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 3, ‘data’: ‘Rash’}]
方法#2:使用列表推导
此方法通过构建全新的列表或由所有字典覆盖原始列表来工作,除了具有必须删除的键的字典。
# Python3 code to demonstrate
# to delete dictionary in list
# using list comprehension
# initializing list of dictionaries
test_list = [{"id" : 1, "data" : "HappY"},
{"id" : 2, "data" : "BirthDaY"},
{"id" : 3, "data" : "Rash"}]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension
# to delete dictionary in list
res = [i for i in test_list if not (i['id'] == 2)]
# printing result
print ("List after deletion of dictionary : " + str(res))
The original list is : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 2, ‘data’: ‘BirthDaY’}, {‘id’: 3, ‘data’: ‘Rash’}]
List after deletion of dictionary : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 3, ‘data’: ‘Rash’}]
方法 #3:使用filter() + lambda
filter
函数可用于获取具有所需键的字典,而 lambda函数用于逐一迭代列表元素,然后过滤器可以执行其任务。
# Python3 code to demonstrate
# to delete dictionary in list
# using filter() + lambda
# initializing list of dictionaries
test_list = [{"id" : 1, "data" : "HappY"},
{"id" : 2, "data" : "BirthDaY"},
{"id" : 3, "data" : "Rash"}]
# printing original list
print ("The original list is : " + str(test_list))
# using filter() + lambda
# to delete dictionary in list
res = list(filter(lambda i: i['id'] != 2, test_list))
# printing result
print ("List after deletion of dictionary : " + str(res))
The original list is : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 2, ‘data’: ‘BirthDaY’}, {‘id’: 3, ‘data’: ‘Rash’}]
List after deletion of dictionary : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 3, ‘data’: ‘Rash’}]