1

I want to do an assignment which defaults to another if it fails.

this = {'one':1}
test = this['a'] if this['a'] else "Wololo"

I get a KeyError when I try this. Reason I need a one liner assignment is I have a minimum of five characters which may be in the dictionary and that requires five separate try blocks to check without returning an error.

2
  • Check defaultdict. Commented Oct 30, 2015 at 11:07
  • .get is the real answer, but note that the ternary version would work if you made it this['a'] if 'a' in this else ... Commented Oct 30, 2015 at 11:40

1 Answer 1

3

Use .get and pass a default value, if the key doesn't exist then the default value is returned:

In [267]:
this = {'one':1}
this.get('a','Wololo')

Out[267]:
'Wololo'
Sign up to request clarification or add additional context in comments.

1 Comment

And if you didn't select the second argument, it will return None instead a KeyError :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.