从字典列表中清除空字典

时间:2017-01-24 13:25:47

标签: python list dictionary

我有一个像这样的词典列表:

[{'a':'21'},{},{'b':20'},{'c':'89'},{}]

从此列表清除空字典的最有效方法是什么,最终结果是:

[{'a':'21'},{'b':'20'},{'c':'89'}]

我正在尝试:

new_list_of_dictionaries = []
for dictionary in list_of_dictionaries:
    if dictionary:
        new_list_of_dictionaries.append(dictionary)
return new_list_of_dictionaries

我不认为这可以在O(1)或其他什么地方完成?

4 个答案:

答案 0 :(得分:6)

只需使用列表推导,并过滤布尔真值。空字典被视为 false

return [d for d in list_of_dictionaries if d]

在Python 2中,您还可以使用filter() function,使用None作为过滤器:

return filter(None, list_of_dictionaries)

在Python 3中返回迭代器而不是列表,因此您必须在其上调用list()(所以return list(filter(None, ...))),此时列表理解更具可读性。当然,如果您实际上不需要随机访问结果(因此可以直接访问result[whatever]),那么迭代器可能仍然是个好主意。

请注意,此 需要花费O(N)时间,您必须测试每个字典。即使列表具有某种自动更新的映射,可以让您在O(1)时间内获取字典的索引,但从列表中删除项目需要向后移动条目。

答案 1 :(得分:4)

理解或filterPython2Python3):

return filter(None, list_of_dictionaries)

# Python3, if you prefer a list over an iterator
return list(filter(None, list_of_dictionaries))  

None作为过滤器函数将过滤掉所有非真实元素,在空集合的情况下,它会非常简洁。

答案 2 :(得分:3)

可以使用列表理解吗?

public void TestMethod()
{
    try
    {
        // can throw an exception specific to the project or a .Net exception 
        SomeWorkMethod() 
    }
    catch(Exception ex) when (!(ex is SpecificException))
    {
        throw new SpecificException(ex);
    }
}

答案 3 :(得分:-2)

我是这样做的

d = [{'a': '21'}, {}, {'b': 20}, {'c': '89'}, {}]
new_d = []
for item in d:
    check = bool(item)
    if not check:
        del item
    else:
        new_d.append(item)

print(new_d)

[{' a':' 21'},{' b':20},{' c':&#39 ; 89'}]

相关问题