Python - Remove dicts with empty values from list of dictionaries

牧云@^-^@ 提交于 2021-01-28 05:32:02

问题


I'd like to remove the list of dictionaries elements that have empty values.

So for the following:

dict = [{"end": "00:15", "item": "Paul Test 1", "start": "00:00"}, {"end": "00:14", "item": "Paul Test 2 ", "start": "00:30"}, {"end": "", "item": "", "start": ""},  {"end": "", "item": "", "start": ""}, {"end": "", "item": "", "start": ""}]

would return a new dict of:

[{"end": "00:15", "item": "Paul Test 1", "start": "00:00"}, {"end": "00:14", "item": "Paul Test 2 ", "start": "00:30"}]

I've tried:

{k:v for k,v in dict if not v}

but I'm getting:

ValueError: too many values to unpack (expected 2)

回答1:


Try this:

print([d for d in arr if all(d.values())])

Don't use dict as a name: you override Python's one. And in your case it's not a dictionary, it is an array of dictionaries.



来源:https://stackoverflow.com/questions/46037007/python-remove-dicts-with-empty-values-from-list-of-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!