19

我想从值创建一个字典,我从 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}

关于如何创建这本词典的任何想法?

4

9 回答 9

45

或者你可以试试熊猫

from pandas import *
xls = ExcelFile('path_to_file.xls')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()
于 2013-01-07T12:38:36.093 回答
19
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
于 2013-01-07T12:34:46.467 回答
16

此脚本允许您将 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
于 2016-01-27T10:35:45.733 回答
4

您可以使用 Pandas 来执行此操作。导入 pandas 并将 excel 作为 pandas 数据框读取。

import pandas as pd
file_path = 'path_for_your_input_excel_sheet'
df = pd.read_excel(file_path, encoding='utf-16')

您可以使用pandas.DataFrame.to_dict将 pandas 数据框转换为字典。在此处找到相同的文档

df.to_dict()

这将为您提供您阅读的 excel 表的字典。

通用示例:

df = pd.DataFrame({'col1': [1, 2],'col2': [0.5, 0.75]},index=['a', 'b'])

>>> df

col1 col2 a 1 0.50 b 2 0.75

>>> df.to_dict()

{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

于 2018-12-26T10:02:10.703 回答
1

我会去:

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)))
于 2013-01-07T12:47:13.910 回答
1

还有一个 PyPI 包:https ://pypi.org/project/sheet2dict/ 它正在解析 excel 和 csv 文件并将其作为字典数组返回。每行都表示为数组中的字典。

像这样:

Python 3.9.0 (default, Dec  6 2020, 18:02:34)
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

# Import the library
>>> from sheet2dict import Worksheet

# Create an object
>>> ws = Worksheet()

# return converted rows as dictionaries in the array 
>>> ws.xlsx_to_dict(path='Book1.xlsx')
[
    {'#': '1', 'question': 'Notifications Enabled', 'answer': 'True'}, 
    {'#': '2', 'question': 'Updated', 'answer': 'False'}
]
于 2021-02-08T10:23:50.707 回答
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
于 2015-02-10T18:34:56.630 回答
0

如果你使用,openpyxl 下面的代码可能会有所帮助:

import openpyxl
workbook = openpyxl.load_workbook("ExcelDemo.xlsx")
sheet = workbook.active
first_row = [] # The row where we stock the name of the column
for col in range(1, sheet.max_column+1):
    first_row.append(sheet.cell(row=1, column=col).value)
data =[]
for row in range(2, sheet.max_row+1):
    elm = {}
    for col in range(1, sheet.max_column+1):
        elm[first_row[col-1]]=sheet.cell(row=row,column=col).value
    data.append(elm)
print (data)

归功于:Python 从 excel 数据创建字典

于 2021-05-14T10:17:32.373 回答
0

如果您想使用 pandas 将 Excel 数据转换为 python 中的字典列表,最好的方法是:

excel_file_path = 'Path to your Excel file'
excel_records = pd.read_excel(excel_file_path)
excel_records_df = excel_records.loc[:, ~excel_records.columns.str.contains('^Unnamed')]
records_list_of_dict=excel_records_df.to_dict(orient='record')
Print(records_list_of_dict)
于 2021-05-08T10:13:07.023 回答