Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put list into dict with first row header as keys

Tags:

I have the following python list:

[['A,B,C,D'],
 ['1,2,3,4'],
 ['5,6,7,8']]

How can I put it into a dict and use the first sub list as the keys?:

{'A': '1',
 'B': '2',
 'C': '3',
 'D': '4'}
{'A': '5',
 'B': '6',
 'C': '7',
 'D': '8'}

Thanks in advance!

like image 950
Sledro Avatar asked Oct 17 '16 22:10

Sledro


1 Answers

You can zip the first element of the list with the remaining elements of the list after splitting the string in each sublist:

# to split string in the sublists
lst = [i[0].split(',') for i in lst]

[dict(zip(lst[0], v)) for v in lst[1:]]

#[{'A': '1', 'B': '2', 'C': '3', 'D': '4'},
# {'A': '5', 'B': '6', 'C': '7', 'D': '8'}]
like image 105
Psidom Avatar answered Oct 11 '22 10:10

Psidom