Home > Software engineering >  Can I retrieve a dictionary value with a "else key" in a lambda function? [duplicate]
Can I retrieve a dictionary value with a "else key" in a lambda function? [duplicate]

Time:09-22

Look this code:

arg = 'yes'
(lambda x: dict(yes=1, no=0)[x])(arg)

It returns:

1

But I'd like to return arg itself if arg is not 'yes' or 'no'. Something like:

arg = 'maybe'
(lambda x: dict(yes=1, no=0, x=x)[x])(arg)

I'm getting a error here...

Can I do that? How to do that?

CodePudding user response:

If you want to use lambda try this:

arg = 'maybe'
(lambda x: dict(yes=1, no=0).get(x,x))(arg)
# maybe
  • Related