7

So, I'm aware that, in Python I can do this:

variable_name = other_variable or 'something else'

...and that that will assign 'something else' to variable_name if other_variable is falsy, and otherwise assign other_variable value to variable.

Can I do a nice succinct similar thing with a dict:

variable_name = my_dict['keyname'] or 'something else'

...or will a non-existent keyname always raise an error, cause it to fail?

1
  • 2
    use the get method my_dict.get('keyname', 'something else') Commented Nov 12, 2018 at 13:18

1 Answer 1

9

You will see KeyError if 'keyname' does not exist in your dictionary. Instead, you can use:

variable_name = my_dict.get('keyname', False) or 'something else'

With this logic, 'something else' is assigned when either 'keyname' does not exist or my_dict['keyname'] is Falsy.

Sign up to request clarification or add additional context in comments.

6 Comments

You answer is correct, but I'd like to point out that what we usually need in this scenario is my_dict.get('keyname', 'something else').
@Gabriel, No, my_dict.get('keyname', 'something else') will be incorrect for my_dict = {'key_name':0}. In this scenario, OP will want 'something else'.
I know and that's why I said your answer is correct. I just noted that when dealing with dicts we USUALLY (not always) want a default for missing keys, not falsey values.
OP was 100% clear and that's why I can say you're correct (otherwise I couldn't say that for sure). My previous advise is for anyone who can read your answer, not only OP. For example, if someone had optional arguments in a function (as in f(a=None)) and converted to kwargs, one would want to test for missing keys, not falsey values. It may not be obvious by reading your answer, so I left an advice. I wasn't implying your answer is wrong.
Thanks! To be honest, I didn't think I meant this, but it's made me realise that this scenario is exactly what I need. :)
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.