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

Abr*_*hih 1 python dictionary list-comprehension dictionary-comprehension

mylist = [{"a" : 1, " b" : 2}, {"c" : 1, "d" :2}]
Run Code Online (Sandbox Code Playgroud)

我的清单就是这样的.我如何删除包含密钥'a'的整个字典?

Moi*_*dri 5

您可以使用列表推导来创建一个dict没有'a'键的s 的新列表:

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

>>> [d for d in mylist if 'a' not in d]
[{'c': 1, 'd': 2}]
Run Code Online (Sandbox Code Playgroud)

如果必须从原始列表中删除元素,那么您可以执行以下操作:

>>> 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}]
Run Code Online (Sandbox Code Playgroud)