setdefault for python dictionaries

setdefault is a very easy way to append values to a dictionary without having to check if the keys are already there or not.

>>> dictionary = {}
>>> dictionary['key1'].append(1)
KeyError: 'a'

and now using setdefault

>>> dictionary = {}
>>> dictionary.setdefault('key1', []).append(1)
>>> dictionary
{'key1': [1]}

Links:

python anti-patterns