Null coalescing on a dict entry in python
Asked Answered
F

1

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?

Fermat answered 12/11, 2018 at 13:17 Comment(1)
use the get method my_dict.get('keyname', 'something else')Cropdusting
C
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.

Cathrine answered 12/11, 2018 at 13:20 Comment(6)
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').Dryad
@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'.Cathrine
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.Dryad
@Gabriel, OK, I thought OP was very clear in his/her explanation. We'll wait to see if there's more clarification.Cathrine
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.Dryad
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. :)Fermat

© 2022 - 2024 — McMap. All rights reserved.