 <p>I believe you can use the defaultdict in the collections module for this. <a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="nofollow">http://docs.python.org/library/collections.html#collections.defaultdict</a></p> <p>I think the examples are pretty close to being exactly what you want.</p>