Sledro Sledro - 1 month ago 14
Python Question

Put list into dict with first row header as keys

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!

Answer

Let's start with your data as presented in the question:

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

Now, let's convert that to the desired list of dictionaries:

>>> [dict(zip(a[0][0].split(','), c[0].split(','))) for c in a[1:]]
[{'A': '1', 'C': '3', 'B': '2', 'D': '4'}, {'A': '5', 'C': '7', 'B': '6', 'D': '8'}