Nested defaultdicts
<p>Why does the below work</p>

<pre><code>x = defaultdict(dict)
for a,b,c in [('eg', 'ef', 'ee'), ('eg', 'eu', 'e4'), ('kk', 'nn', 'bb')]:
    x[a][b] = c
</code></pre>

<p>And the below throws an error ?</p>

<pre><code>x = defaultdict(dict)
for a,b,c,d in [('eg', 'ef', 'ee', 'gg'), ('eg', 'eu', 'e4', 'hh'),
                ('kk', 'nn', 'bb', 'ff')]:
    x[a][b][c] = d
</code></pre>

<p>The issue here is that <code>defaultdict</code>  accepts a callable, which is used as a factory to generate the value when a key is missing.  Once you understand that, the behaviour is clear:</p>

<pre><code>x = defaultdict(dict)
x                    # it's a default dict
x['a']               # it's just a dict()
x['a']['b'] = 'c'    # it's just setting the 'b' item in the dict x['a']
x['a']['b']['z']     # oops, error, because x['a']['b'] is not a dict!
</code></pre>

<p>If you only require a finite level of nesting, using a plain old <code>dict</code> with <code>tuple</code> keys is usually a much easier data structure to work with.  That will work fine for both the 2-d and 3-d examples shown in your question.  </p>

<p>If you require arbitrary levels of nesting, however, you can consider the recursive <code>defaultdict</code> example shown <a href="http://stackoverflow.com/a/19189356/674039">here</a>.</p>

python python-2.7