Reputation: 43
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.
Upvotes: 4
Views: 9365
Reputation: 104
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!
Upvotes: 3
Reputation: 3827
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))
Upvotes: 3
Reputation: 178
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))
Upvotes: 1
Reputation: 10624
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']}
Upvotes: 5