Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null coalescing on a dict entry in python

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?

like image 939
Owen C. Jones Avatar asked Jul 29 '26 23:07

Owen C. Jones


1 Answers

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.

like image 98
jpp Avatar answered Jul 31 '26 14:07

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!