how to scrutch a dict()

John Nagle nagle at animats.com
Thu Oct 21 12:44:12 EDT 2010


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.

				John Nagle



More information about the Python-list mailing list