John Nagle wrote:
On 10/20/2010 9:32 PM, Phlip wrote:

Not Hyp:

def _scrunch(**dict):
     result = {}

     for key, value in dict.items():
         if value is not None:  result[key] = value

     return result

That says "throw away every item in a dict if the Value is None".

Are there any tighter or smarmier ways to do that?


Yes.

class nonnulldict(dict) :
    def __setitem__(self, k, v) :
        if not (v is None) :
           dict.__setitem__(self, k, v)

That creates a subclass of "dict" which ignores stores of None values.
So you never store the unwanted items at all.

It's going to take more work than that...

--> nnd = nonnulldict(spam='eggs', ham=None, parrot=1)
--> nnd
{'ham': None, 'parrot': 1, 'spam': 'eggs'}
--> d['more_hame'] = None
--> nnd.update(d)
--> nnd
{10000:True, 'more_hame':None, 'ham':None, 'parrot':1, 'spam':'eggs'}

Tested in both 2.5 and 3.1.

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to