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?
collections.defaultdict
. \$\endgroup\$ – Jeff Mercado Apr 25 '13 at 8:32