hovo hovo - 3 months ago 8
Python Question

creating nested dicts in python 3

I'm trying to create the following nested dict structure,

{0: {0: 1}, 1: {0: 1, 1: 1}}
with the following code:

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


but all I'm getting
feats = {}
. Why is that? Thanks.

Answer

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

You can fix your code like below:

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

print(feats)

output:

{0: {0: 1}, 1: {0: 1, 1: 1}}