简体   繁体   中英

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.

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

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM