【问题标题】:Looking to load Excel values into a dictionary希望将 Excel 值加载到字典中
【发布时间】:2019-12-31 17:37:39
【问题描述】:

我正在尝试将 Excel 文件加载到 Python 字典中并使其遵循特定格式。

这是 Excel 文件:

这是我要输出的字典:

sheet1  = {'WLE-1-101':{'Max Height':8.19, 'Max Width':4.0, 'Laps':1},
           'WLE-1-102':{'Max Height':8.83, 'Max Width':4.0, 'Laps':2},
           'WLE-1-103':{'Max Height':9.47, 'Max Width':4.0, 'Laps':2}}

到目前为止我有这个代码:

import xlrd
import pprint


loc = ('C:\example.xlsx')
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_name('Sheet1')
sheet1 = {}

for i in range(sheet.nrows):
    if i >= 1:
        row = sheet.row_values(i)
        for cell in row:
            print(cell)

哪个输出这个:

WLE-1-101
8.19
4.0
30.95
143.13
1
1.0


WLE-1-102
8.83
4.0
32.92
152.28
1
2.0


WLE-1-103
9.47
4.0
34.91
161.45
1
2.0


WLE-1-104
2.0
4.0
6.99
32.33
1
1.0


WLE-2-105
2.0
3.9
7.67
35.45
0
1.0


WLE-2-106
10.0
4.0
38.23
176.83
1
2.0


WLE-2-107
10.0
4.0
38.7
178.99
1
2.0


WLE-2-108
10.0
4.0
38.19
176.65
1
2.0


WLE-2-109
2.0
3.9
7.66
35.42
0
1.0


WLE-3-110
2.0
4.0
6.99
32.35
1
1.0


WLE-3-111
9.47
4.0
34.92
161.5
1
2.0


WLE-3-112
8.83
4.0
32.92
152.27
1
2.0


WLE-3-113
8.19
4.0
30.92
143.02
1
1.0

【问题讨论】:

  • 您能否以 csv 格式提供 xlsx 数据或将示例剥离为几行数据? Images of code/data 真的很难使用。如果我想运行它,我必须手动输入它。谢谢。

标签: python excel dictionary xlrd


【解决方案1】:

您可以像这样对数据进行分组:

for i in range(sheet.nrows):
    if i >= 1:
        wle, height, width, sq, weight, wide, laps = sheet.row_values(i)
        sheet1[wle] = {
          'Max Height': height,
          'Max Width': widht,
          'Laps': laps
        }

print(sheet1)

【讨论】:

  • 这看起来是个好方法,但它给了我一个值错误:
  • wle,height,width,sq,weight,wide,laps = sheet.row_values(i) ValueError: too many values to unpack (expected 7) 我试过 .split(","),但是got AttributeError: 'list' object has no attribute 'split' 任何建议将不胜感激。
  • 问题出在你的数据上,因为如果每一行都包含这些值,它们应该能够被解包。 print(sheet.row_values(i)) 查看是否所有行都有这些值。 @bmorton
  • 好提示!将文件格式更改为 xlsm 使其工作。谢谢!
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2020-06-11
  • 1970-01-01
  • 2019-05-03
相关资源
最近更新 更多