python reading table into list of dicts

Task:
create a list of dict from a table. First row of the table is header and rest is data. Each row should be converted to a dict where keys are header value and values are data.

Example:

header1 header2 header3
x1 x2 x3
y1 y2 y3
z1 z2 z3

Code:

table=[
['header1','header2','header3'],
['x1','x2','x3'],
['y1','y2','y3'],
['z1','z2','z3'],
]

header=table[0]
print [dict(zip(header,table[rowx])) for rowx in range(1,len(table))]

Output:

[{'header2': 'x2', 'header3': 'x3', 'header1': 'x1'}, {'header2': 'y2', 'header3': 'y3', 'header1': 'y1'}, {'header2': 'z2', 'header3': 'z3', 'header1': 'z1'}]
Advertisements