Skip to main content
 首页 » 编程设计

python之如何删除列表中的整个字典

2025年05月04日11qlqwjy

mylist = [{"a" : 1, " b" : 2}, {"c" : 1, "d" :2}] 

我的 list 是这样的。我将如何删除包含键“a”的整个字典?

请您参考如下方法:

您可以使用 list comprehension 使用 dict 来创建一个新列表,而无需 'a' 键,如下所示:

>>> mylist = [{"a" : 1, " b" : 2},{"c" : 1, "d" :2}] 
 
>>> [d for d in mylist if 'a' not in d] 
[{'c': 1, 'd': 2}] 

如果必须从原始列表中删除元素,那么您可以这样做:

>>> mylist = [{"a" : 1, " b" : 2},{"c" : 1, "d" :2}] 
 
#                           v Iterate over the copy of the list, 
#                           v    so that the change in index after the  
#                           v    deletion of  elements in the list won't  
#                           v    impact the future iterations 
>>> for i, d in enumerate(list(mylist)): 
...     if 'a' in d: 
...         del mylist[i] 
... 
>>> mylist 
[{'c': 1, 'd': 2}]