views:

126

answers:

4

Is it possible to:

for k,v in kwargs.items()
    if v == None or v == '' or v == 1.0 or v == False:
       del kwargs[k]

without deleting the key if v == 0.0? (False seems to equal 0.0), and without deleting the keys who equal True.

+6  A: 

You should use v is False instead of v == False. The same applies for your comparison to None. See PEP 8 - Style Guide for Python:

Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.

Mark Byers
You absolutely *should* (applies to all singletons, e.g. `True` and `None`).
delnan
@delnan: Yes, you are right. I changed the wording and added some more detail.
Mark Byers
...and if you do, you can drop the `or v ==''` part.
Tim Pietzcker
+2  A: 

Slow down guys with your advice, from PEP 8:

Don't compare boolean values to True or False using ==

   Yes:   if greeting:

   No:    if greeting == True:

   Worse: if greeting is True:

Also comparing float value you should not use == but

abs(x-other) < verysmall

Tony Veijalainen
`if not x` beats `if x == False`, for sure. But here, the question is how to check if something really is the boolean value `False`, not something "falsy".
delnan
+3  A: 

Or you can put it like this :

if v in (None, '', 1.0) or v is False:
singularity
Nope. `0.0 in (None,'',1.0,False)` -> True because the linear search `in` of sequences uses `==` (which is usually the wanted behaviour, but not here).
delnan
@delnan: yes , i just change it , the problem is with False , because 0.0 == False , so he should just put "is False"
singularity
Fails for v=True, because 1.0 == True.
Mark Tolonen
@Mark Tolonen: yes you are right but i think Izz has already correct it :)
singularity
A: 

Thanks for your replies. Using the suggestions, the problem was solved:

kwargs = {'None': None, 'empty': '', 'False': False, 'float': 1.0, 'True': True}       
for k,v in kwargs.items():
    if v in (None, '', 1.0) and v is not True:
        del kwargs[k]
    if v is False:
        del kwargs[k]

kwargs
{'True': True}

-->

kwargs = {'None': None, 'empty': '', 'False': False, 'float': 0.0, 'True': True}       
for k,v in kwargs.items():
     if v in (None, '', 1.0) and v is not True:
         del kwargs[k]
     if v is False:
         del kwargs[k]

kwargs
{'True': True, 'float': 0.0}
Izz ad-Din Ruhulessin