Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing dictionary entries with no values- Python

If I have a dictionary, and I want to remove the entries in which the value is an empty list [] how would I go about doing that?

I tried:

for x in dict2.keys():
    if dict2[x] == []:
        dict2.keys().remove(x)

but that didn't work.

like image 574
marsx Avatar asked Jun 10 '11 14:06

marsx


1 Answers

Newer versions of python support dict comprehensions:

dic = {i:j for i,j in dic.items() if j != []}

These are much more readable than filter or for loops

like image 81
JBernardo Avatar answered Sep 19 '22 02:09

JBernardo