Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a dictionary in python?

I have a list of lists like so: N = [[a,b,c],[d,e,f],[g,h,i]]

I would like to create a dictionary of all the first values of each list inside N so that I have;

d = {1:[a,d,g],2:[b,e,h],3:[c,f,i]}

I have tried many things and I cant figure it out. The closest I have gotten:

d = {}
for i in range(len(N)):
    count = 0
    for j in N[i]:
        d[count] = j
        count+=1

But this doesnt give me the right dictionary? I would really appreciate any guidance on this, thank you.

like image 732
DiracPretender Avatar asked Dec 13 '22 07:12

DiracPretender


1 Answers

You can use a dict comprehension (I use N with 4 items, to avoid confusion):

N=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'],['w', 'j', 'l']]

{i+1:[k[i] for k in N] for i in range(len(N[0]))}

#{1: ['a', 'd', 'g', 'w'], 2: ['b', 'e', 'h', 'j'], 3: ['c', 'f', 'i', 'l']}
like image 73
IoaTzimas Avatar answered Dec 23 '22 15:12

IoaTzimas