There are two issues here:
v is not ''
should bev != ''
. You should always use==
and!=
to compare two values becauseis
andis not
are for comparing the identities of two objects.You need to use
and
instead ofor
. Otherwise, this condition:v != '' or v != {} or v is not None
will always be
True
becausev
will always be either not equal to''
or not equal to{}
.
Below is a fixed version of your code:
>>> a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}
>>> a = dict((k, v) for k, v in a.iteritems() if v != '' and v != {} and v is not None)
>>> a
{'sadfa': 'dsf'}
>>>
However, we can simplify this further:
>>> a = {'sd':{},'sdd':'','sadfas':None,'sadfa':'dsf'}
>>> a = dict((k, v) for k, v in a.iteritems() if v)
>>> a
{'sadfa': 'dsf'}
>>>
This solution works because ''
, {}
, and None
all evaluate to False
.