how to scrutch a dict()

John Pinner funthyme at gmail.com
Thu Oct 21 12:30:25 CEST 2010


On Oct 21, 5:40 am, Paul Rubin <no.em... at nospam.invalid> wrote:
> Phlip <phlip2... 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...

As James has suggested, you can 'clean the dict in place (as it's
mutable), you don't have to return a whole new object.

> 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,

Yes, likewise with any other builtin; if you use pychecker and/or
pylint routinely, they would warn you about this.

> since it is a
> built in function (dictionary constructor).

I don't think so:

>>> type(dict)
<type 'type'>
>>>

So you're not running a function, but creating an instance of a dict.

Best wishes,

John
--




More information about the Python-list mailing list