Categories
python

Python: Using get with default or using the or keyword with the default

Say you have some dictionary arriving and you want to ensure the data from the dictionary has an acceptable default for a field..

Should you use a get with a default like this:

my_key = my_dict.get('key', False)

or using python’s or keyword:

my_key = my_dict.get('key') or False

Some Scenarios

Where the key does not exist

get with default:

>>> {}.get('a', False)
False

or keyword:

>>> {}.get('a') or False
False

In this case they work much the same.

Where the key exists and is falsey int

get with default:

>>> {'a': 0}.get('a', False)
0

or keyword;

>>> {'a': 0}.get('a') or False
False

Where the key exists and is falsey str

get with default:

>>> {'a': ''}.get('a', False)
''

or keyword:

>>> {'a': ''}.get('a') or  False
False

Where the key exists and is None

get with default:

>>> {'a': None}.get('a', False)
>>> 

Returns None

or keyword:

>>> {'a': None}.get('a') or False
False

Summary

If you are not expecting valid empty string or 0 values, the best option would be to use or False.

Have not tested performance.