Set a default if key not in a dictionary, *or* value is None Let's say I have a key 'messages' that is usually a list, but might be None, or might not be present. So these are all valid inputs:

{
   'date': 'tuesday',
   'messages': None,
}

{
   'date': 'tuesday',
   'messages': ['a', 'b'],
}

{
   'date': 'tuesday',
}


If I want to retrieve 'messages' from the input, and iterate over them, I need to do something like this:

messages = d.get('messages', []) # Check for key existence
if messages is None:             # Check if key is there, but None
    messages = []
for message in messages:
    do_something()


That seems a little verbose for Python - is there a simpler way to write that?
for message in d.get('messages') or ():
    do_something()



get returns None by default for missing keys.
a or b evaluates to b when bool(a) == False. An empty list and None are examples of values that are false in a boolean context.
Note that you cannot use this trick if you intend to modify the possibly empty list that is already in the dict. I'm using () instead of [] to guard against such mistakes. Also, CPython caches the empty tuple, so using it is slightly faster than constructing an empty list.