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

标签 python dictionary list-comprehension dictionary-comprehension

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}]

关于python - 如何删除列表中的整个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46454836/

相关文章:

functional-programming - Scheme 的列表理解库?

python - 控制MySQLdb中的小数除法精度

python - Networkx 提取特定维度的连通分量子图列表 : incorrect counts

Python:通过让用户编辑默认值来获取用户输入

algorithm - python : List all possible paths in graph represented by dictionary

Python - 在列表理解中保持计数器

python - 使用 bool 表达式生成器展平序列

python - 客户端到服务器,python中的套接字多对一关系

c# - C#抛出异常后的return语句

具有已知键输入的 Python 3 字典