Home > OS >  How can I use nested loop to create the dictionary I want?
How can I use nested loop to create the dictionary I want?

Time:07-16

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?

CodePudding user response:

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_.

CodePudding user response:

Actually you just have to move the dic2[i]=dic outside the second loop


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)

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

You no need to use 2 dictionaries, It can be solved using single dictionary itself. 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}}
  • Related