Song
Song

Reputation: 11

Q: Using python to translate excel --> dictionary

I would like to create a dictionary from an excel file. For example, if data is organized as follows:

x1 1 y1 0 f1 4
x2 2 y2 2 f2 1
x3 3 y3 8 f3 7

I would like to create a dictionary which outputs:

[{'x1': '1', 'y1': '0', 'f1': '4'},{'x2':'2', 'y2':'2','f2':'1'},{'x3':'3','y3':'8','f3':'7'}]

Upvotes: 0

Views: 129

Answers (1)

Wicaledon
Wicaledon

Reputation: 810

import xlrd

# Give the location of the file
loc = ("YOURFILENAME.xls")

# To open Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

my_arr = []

for i in range(sheet.nrows):
    my_dict = {}
    my_dict[str(sheet.cell_value(i, 0))] = str(int(sheet.cell_value(i, 1)))
    my_dict[str(sheet.cell_value(i, 2))] = str(int(sheet.cell_value(i, 3)))
    my_dict[str(sheet.cell_value(i, 4))] = str(int(sheet.cell_value(i, 5)))
    my_arr.append(my_dict)
print(my_arr)

Upvotes: 1

Related Questions