how to scrutch a dict()

Paul Rubin no.email at nospam.invalid
Thu Oct 21 00:40:41 EDT 2010


Phlip <phlip2005 at gmail.com> writes:
> 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? Python does so
> often manage maps better than that...

Untested:

def _scrunch(**kwargs):
   return dict(k,v for k,v in kwargs.iteritems() if v is not None)

Note: it's best not to use "dict" as a parameter name, since it is a
built in function (dictionary constructor).  It's also a bit of a code
smell that you're using keyword args like that.



More information about the Python-list mailing list