4

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.

4 Answers4

5

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']}
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
  • Hi, thanks for the answer, but this is creating a dictionary with items of each list inside N, whereas I would like a dictionary containing lists of first, second, third etc. items in each list inside N? – DiracPretender Feb 13 '21 at 13:53
  • 2
    @bruno that is what I thought first, but the correct ouptut is this one with my current solution – IoaTzimas Feb 13 '21 at 13:53
3

You can transpose the list with zip(*N) and then use enumerate to get the index and the elements into pairs for dict.

>>> dict((i+1, list(j)) for i, j in enumerate(zip(*N)))

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

Alternate based on suggestion by @Vishal Singh

>> dict((i, list(j)) for i, j in enumerate(zip(*N), start=1))
Deepstop
  • 3,627
  • 2
  • 8
  • 21
  • 2
    `enumerate(zip(*N, start=1))` will make it more clean. – Vishal Singh Feb 13 '21 at 14:07
  • Also (1) Unless there is a particular reason, starting the dictionary keys at zero might work out better for you, depending on what the rest of you code is doing, and (2) you might be able to use tuples instead of lists in the output, again depending on your application. Applying both of these: dict(a for a in enumerate(zip(*N))) – Deepstop Feb 13 '21 at 15:39
3

Check the provided code below and output.

N = [[a,b,c],[d,e,f],[g,h,i]]

d = {}

for y in range(0,len(N)):
    tmp=[]
    for x in N:
        tmp.append(x[y])
    d[y+1]=tmp

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

Hope that helps!

1

Here is a simple solution. Just pass your list to this function.

def list_to_dict(lis):
    a=0
    lis2=[]
    dict={}
    n=len(lis)

    while a<n:
        for el in lis:
            lis2.append(el[a])
        dict[a+1]=lis2
        lis2=[]
        a+=1

    return dict

my_list=[["a","b","c"],["d","e","f"],["g","h","i"]]
print(list_to_dict(my_list))
SuperNoob
  • 170
  • 1
  • 10