简体   繁体   English

在python 3中创建嵌套的dicts

[英]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: 我正在尝试使用以下代码创建以下嵌套的dict结构{0: {0: 1}, 1: {0: 1, 1: 1}}

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 = {} . 但所有我都获得了feats = {} Why is that? 这是为什么? Thanks. 谢谢。

The problem here is, you are not storing feat value in feats , so it is lost after every iteration. 这里的问题是,你没有在feats存储feat值,所以它在每次迭代后都会丢失。 At the end of the iterations, feats is empty. 在迭代结束时, feats是空的。

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}}

First of all I ran your program and I printed feats, it printed{0: 1, 1: 1} and not {} 首先,我运行了你的程序,我打印了专辑,它打印{0:1,1:1}而不是{}

Second thing, what I can understand from your requirement is that, in a generic way, while looping through a range of numbers, you want to have that number as key and value as dictionary containing key value pairs, where number of keys are from 0 to that number and value as 1. Correct me if I am wrong. 第二件事,我可以从你的要求中理解的是,以通用的方式,在循环遍历一系列数字时,你希望将该数字作为键和值作为包含键值对的字典,其中键的数量来自0这个数字和价值为1.如果我错了,请纠正我。

So the correct program for this would be: 所以正确的程序是:

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

You can replace 2 with any number in range and get your answer accordingly. 你可以用范围内的任何数字替换2并相应地得到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM