A very elegant way (since Python 2.5) is to use the defaultdict from the collections module:
>>> from collections import defaultdict >>> h = defaultdict(list) >>> h['a'].append('b') >>> h defaultdict(<type 'list'>, {'a': ['b']})
defaultdict is like a dict, but provides a default value using any constructor that you passed to it when you created it (in this example, a list).
I especially like this with the setdefault dict method, because 1) you define the variable as defaultdict, and in general no other changes are required for the code (except, perhaps, to remove previous kludges for default values); and 2) setdefault - scary name: P
source share