2013-01-07 40 views
5

Tôi muốn tạo ra một từ điển từ các giá trị, tôi nhận được từ các tế bào excel, Mã của tôi là dưới đây,Python Tạo từ điển từ dữ liệu excel

wb = xlrd.open_workbook('foo.xls') 
sh = wb.sheet_by_index(2) 
for i in range(138): 
    cell_value_class = sh.cell(i,2).value 
    cell_value_id = sh.cell(i,0).value 

và tôi muốn tạo ra một từ điển, như dưới đây, mà bao gồm các giá trị đến từ các tế bào excel;

{'class1': 1, 'class2': 3, 'class3': 4, 'classN':N} 

Bất kỳ ý tưởng nào về cách tạo từ điển này?

Trả lời

9
d = {} 
wb = xlrd.open_workbook('foo.xls') 
sh = wb.sheet_by_index(2) 
for i in range(138): 
    cell_value_class = sh.cell(i,2).value 
    cell_value_id = sh.cell(i,0).value 
    d[cell_value_class] = cell_value_id 
+0

này là khá nhiều những gì tôi đã suy nghĩ ... – mgilson

+0

là 'd' một đối tượng từ điển hoặc bất kỳ mảng? –

+0

@PythonLikeYOU - theo 'd = {}', nó là một từ điển. – eumiro

19

hoặc bạn có thể thử pandas

from pandas import * 
xls = ExcelFile('path_to_file.xls') 
df = xls.parse(xls.sheet_names[0]) 
print df.to_dict() 
+0

'+ 1' cho bạn cho khái niệm này không! –

0

tôi muốn đi cho:

wb = xlrd.open_workbook('foo.xls') 
sh = wb.sheet_by_index(2) 
lookup = dict(zip(sh.col_values(2, 0, 138), sh.col_values(0, 0, 138))) 
0

nếu bạn có thể chuyển nó sang csv này là rất thích hợp.

import dataconverters.commas as commas 
filename = 'test.csv' 
with open(filename) as f: 
     records, metadata = commas.parse(f) 
     for row in records: 
      print 'this is row in dictionary:'+row 
5

kịch bản này cho phép bạn chuyển đổi một bảng dữ liệu excel vào một danh sách các từ điển:

import xlrd 

workbook = xlrd.open_workbook('foo.xls') 
workbook = xlrd.open_workbook('foo.xls', on_demand = True) 
worksheet = workbook.sheet_by_index(0) 
first_row = [] # The row where we stock the name of the column 
for col in range(worksheet.ncols): 
    first_row.append(worksheet.cell_value(0,col)) 
# transform the workbook to a list of dictionaries 
data =[] 
for row in range(1, worksheet.nrows): 
    elm = {} 
    for col in range(worksheet.ncols): 
     elm[first_row[col]]=worksheet.cell_value(row,col) 
    data.append(elm) 
print data 
Các vấn đề liên quan