Have do_nothing as default action for dictionary?
Chris Angelico
rosuav at gmail.com
Sun Sep 3 16:00:12 EDT 2017
On Mon, Sep 4, 2017 at 5:31 AM, Christopher Reimer via Python-list
<python-list at python.org> wrote:
> Greetings,
>
> I was playing around this piece of example code (written from memory).
>
>
> def filter_text(key, value):
>
> def do_nothing(text): return text
>
> return {'this': call_this,
>
> 'that': call_that,
>
> 'what': do_nothing
>
> }[key](value)
>
>
> Is there a way to refactor the code to have the inner do_nothing function be
> the default action for the dictionary?
Easy: use the .get() method.
return {'this': call_this,
'that': call_that,
}.get(key, do_nothing)(value)
ChrisA
More information about the Python-list
mailing list