Sunday, 1 September 2013

xlrd spreadsheet to python list of dicts

xlrd spreadsheet to python list of dicts

I have a spreadsheet and Im using xlrd to parse to python.

I need to wrangle it (including the other sheets) into a list of dicts
like such:
[{"price4-0": 18.22, "price4-1": 21.23, "price4-4": 25.65, "quantity":
100.0, "turnaround": "1days", "size": "2 x 2"},
{"price4-0": 16.44, "price4-1": 19.43, "price4-4": 23.54, "quantity":
200.0, "turnaround": "1days", "size": "2 x 2"}...]
so 'turnaround' dict value is taken from the sheetname, and the other dict
keys are the first row value. I am trying to write it so if another sheet
or another row is added it will still work. Basically loop through and add
the right values in the right place. I have a hardcoded version which
gives correct result but it needs to be dynamic:
from pprint import pprint
import xlrd
wb = xlrd.open_workbook('cardprice.xls')
pricelist = []
for i, x in enumerate(wb.sheets()):
for r in range(x.nrows)[1:]:
row_values = x.row_values(r)
pricelist.append({'turnaround':x.name,
'size':row_values[0],
'quantity':row_values[1],
'price4-0':row_values[2],
'price4-1':row_values[3],
'price4-4':row_values[4]
})
pprint(pricelist)

No comments:

Post a Comment