2013-01-07 62 views
5

我想創建從值的字典創建字典,我從Excel單元格, 我的代碼如下得到,Python從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 

,我想創建一個字典,如下圖所示,即由來自excel單元的值組成;

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

關於如何創建該詞典的任何想法?

回答

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

這是一個很值得我在想什麼... – mgilson

+0

是'D'的字典對象或任何陣列? –

+0

@PythonLikeYOU - 根據'd = {}',它是一本字典。 – eumiro

19

,或者你可以嘗試pandas

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

'+ 1'給你的概念! –

0

我會去:

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

,如果你可以把它轉換到csv這是非常合適的。

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

該腳本可以讓你的Excel數據錶轉換成詞典列表:

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