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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s