how to scrutch a dict()

Chris Rebert clp2 at rebertia.com
Thu Oct 21 00:50:33 EDT 2010


On Wed, Oct 20, 2010 at 9:40 PM, Paul Rubin <no.email at nospam.invalid> wrote:
> 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)

Also, in Python 3, one can instead use a dict comprehension (see PEP
274: http://www.python.org/dev/peps/pep-0274/ ), which makes this a
bit more elegant:

result = {k:v for k,v in kwargs.items() if v is not None}

Cheers,
Chris
--
"Smarmy" code; now there's an interesting concept.
http://blog.rebertia.com



More information about the Python-list mailing list