creating nested dicts in python 3
<p>I'm trying to create the following nested dict structure, <code>{0: {0: 1}, 1: {0: 1, 1: 1}}</code> with the following code:</p>

<pre><code>feats = {}
for i in range(2):
    feat = feats.get(i, {})
    for j in range(i+1):
        feat[j] = 1
</code></pre>

<p>but all I'm getting <code>feats = {}</code>. Why is that? Thanks.</p>

<p>The problem here is, you are not storing <code>feat</code> value in <code>feats</code>, so it is lost after every iteration. At the end of the iterations, <code>feats</code> is empty.</p>

<p>You can fix your code like below: </p>

<pre><code>feats = {}
for i in range(2):
    feat = feats.get(i, {})
    for j in range(i+1):
        feat[j] = 1
    feats[i] = feat

print(feats)
</code></pre>

<p>output:</p>

<pre><code>{0: {0: 1}, 1: {0: 1, 1: 1}}
</code></pre>

python python-3.x dictionary