how to scrutch a dict()

Ben Finney ben+python at benfinney.id.au
Thu Oct 21 00:52:08 EDT 2010


Phlip <phlip2005 at gmail.com> writes:

> Not Hyp:

I don't know what this means; I hope it's not important.

> def _scrunch(**dict):

You're clobbering the built-in ‘dict’ binding here.

You're also requiring the input to be keyword parameters. Why not simply
take a single parameter, and allow the *caller* to decide if they want
to split up the key-value pairs?

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

I'm not sure “smarmy” means what you think it means; you might be amused
to read a dictionary definition for that word.

As for your code, it seems simple enough as is. You could translate it
to a generator expression and feed that to the ‘dict’ constructor::

    out_dict = dict(
        (key value) for (key, value) in in_dict.items()
        if value is not None)

but that loses the utility of having it all wrapped up in a function,
which would be my preference::

    def scrunchdict(in_dict):
        out_dict = dict(
            (key value) for (key, value) in in_dict.items()
            if value is not None)
        return out_dict

-- 
 \        “Some people, when confronted with a problem, think ‘I know, |
  `\       I'll use regular expressions’. Now they have two problems.” |
_o__)                           —Jamie Zawinski, in alt.religion.emacs |
Ben Finney



More information about the Python-list mailing list