【问题标题】:How do i delete a whole dictionary inside a list?如何删除列表中的整个字典?
【发布时间】:2017-09-27 18:28:27
【问题描述】:
mylist = [{"a" : 1, " b" : 2}, {"c" : 1, "d" :2}]

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

【问题讨论】:

  • 这总是第一本字典吗?如果有两个字典的键为“a”怎么办?
  • {d for d in mylist if 'a' not in d}?
  • 让我们先试试'如果只有一个字典的键'a'。我是 python 的初学者,我想慢慢来,理解得很好

标签: python dictionary list-comprehension dictionary-comprehension


【解决方案1】:

您可以使用 list comprehension 创建一个带有 dicts 而没有 '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}]

【讨论】:

    【解决方案2】:

    在你说的cmets里

    我是 python 的初学者,我想慢慢来,理解得很好

    所以我将重点放在解释步骤上,而不是直接给你解决方案。

    检查 one 字典是否包含特定键的最简单方法是使用in

    >>> d = {'a': 10, 'b': 20}
    >>> 'a' in d
    True
    
    >>> 'c' in d
    False
    

    同样,您可以使用not in 来检查它是否不是字典中的键:

    >>> 'c' not in d
    True
    
    >>> 'b' not in d
    False
    

    由于您正在处理一个字典列表,因此您需要对其进行迭代。使用 Python,您可以使用 for 遍历每个元素:

    >>> list_of_dicts = [{'a': 10, 'b': 20}, {'b': 10, 'c': 20}]
    >>> for subdict in list_of_dicts:
    ...     print(subdict)
    ... 
    {'a': 10, 'b': 20}
    {'b': 10, 'c': 20}
    

    因此,您基本上只需将for 循环与检查键是否为in 子字典结合起来。但是,修改当前迭代的内容并不是一个好主意,因此您可以创建一个新列表来存储要保留的字典:

    >>> keep_these = []
    >>> for subdict in list_of_dicts:
    ...     if 'a' not in subdict:
    ...         keep_these.append(subdict)
    ...
    >>> keep_these
    [{'b': 10, 'c': 20}]
    

    在 Python 中有一种更简单的方法:列表推导式。 Moinuddin Quadri 已经介绍过,但只是重复一遍:

    >>> [subdict for subdict in list_of_dicts if 'a' not in subdict]
    [{'b': 10, 'c': 20}]
    

    这本质上与我上面使用的for 循环完全相同,但它更短、更快。

    【讨论】:

    • 描述性强,解释清楚 (+1)
    • 谢谢。解释清楚,易于理解!
    【解决方案3】:

    你也可以使用filter来解决这个问题:

    mylist = [{"a" : 1, " b" : 2}, {"c" : 1, "d" :2}]
    new_list = list(filter(lambda x: "a" not in x, mylist))
    

    输出:

    [{'c': 1, 'd': 2}]
    

    关于您最近的评论,删除值为“apple”的字典:

    mylist = [{"a" : "apple", "b" : "orange"}, {"c" : "pineapple", "d" : "mango"}]
    final_list = list(filter(lambda x:"apple" not in x.values(), mylist))
    

    【讨论】:

    • 完美运行。谢谢,我有一个后续问题,如果我的列表是这样的,mylist = [{"a" : apple, "b" : orange}, {"c" : pineapple, "d" : mango}] 会怎样我删除了包含单词“apple”的字典?
    • 完美。太感谢了。我搜索了很多谷歌以获得明确的解释和答案。现在我知道了。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2019-09-16
    相关资源
    最近更新 更多