[英]How can I use nested loop to create the dictionary I want?
I want to create a dictionary like :我想创建一个像这样的字典:
{0: {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
1: {0: 6, 1: 7, 2: 8, 3: 9, 4: 10},
2: {0: 11, 1: 12, 2: 13, 3: 14, 4: 15},
3: {0: 16, 1: 17, 2: 18, 3: 19, 4: 20}}
And this is my code :这是我的代码:
list=[[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]]
dic={}
dic2={}
for i in range(len(list)):
for x in range(len(list[i])):
dic[x] = list[i][x]
dic2[i]=dic
print(dic2)
And the result is :结果是:
{0: {0: 16, 1: 17, 2: 18, 3: 19, 4: 20},
1: {0: 16, 1: 17, 2: 18, 3: 19, 4: 20},
2: {0: 16, 1: 17, 2: 18, 3: 19, 4: 20},
3: {0: 16, 1: 17, 2: 18, 3: 19, 4: 20}}
Where did I make mistake?我在哪里犯错了? How can I fix it?我该如何解决?
Another way to do this would be:另一种方法是:
dic = {
lst_ind: {i_ind: i for i_ind, i in enumerate(lst)}
for lst_ind, lst in enumerate(list)
}
And by the way I would avoid using names of python builtins such as list
as variable names as this can cause problems, better use something like lst
or list_
.顺便说一句,我会避免使用 python 内置函数的名称,例如list
作为变量名,因为这可能会导致问题,最好使用lst
或list_
类的名称。
Actually you just have to move the dic2[i]=dic
outside the second loop实际上,您只需将dic2[i]=dic
移到第二个循环之外
list=[[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]]
dic2={}
for i in range(len(list)):
dic={}
for x in range(len(list[i])):
dic[x] = list[i][x]
dic2[i]=dic
print(dic2)
Try:尝试:
f, s = 4,5
dct = {}
for i in range(f):
dct[i] = {j : i*s+(j+1) for j in range(s)}
print(dct)
# As one-line
# dct = {i : {j : i*s+(j+1) for j in range(s)} for i in range(f)}
{0: {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
1: {0: 6, 1: 7, 2: 8, 3: 9, 4: 10},
2: {0: 11, 1: 12, 2: 13, 3: 14, 4: 15},
3: {0: 16, 1: 17, 2: 18, 3: 19, 4: 20}}
Try:尝试:
list=[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
dict2={}
for i in range(len(list)):
dic={}
for x in range(len(list[i])):
dic[x]=list[i][x]
dic2[i]=dic
print(dic2)
You no need to use 2 dictionaries, It can be solved using single dictionary itself.您无需使用 2 个字典,可以使用单个字典本身来解决。 Hope this helps.希望这可以帮助。
dic = {}
for i in range(len(list)):
dic[i] = { j: l[i][j] for j in range(len(list[i]))}
print(dic)
the outupt for the above code is上述代码的输出是
{0: {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
1: {0: 6, 1: 7, 2: 8, 3: 9, 4: 10},
2: {0: 11, 1: 12, 2: 13, 3: 14, 4: 15},
3: {0: 16, 1: 17, 2: 18, 3: 19, 4: 20}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.