[英]Using python and xlrd, what is the best way to read 2 columns from a spreadsheet
I have an excel spreadsheet that has 2 columns. 我有一个具有2列的Excel电子表格。 Something like this
像这样
|ColA | | ColA | ColB |
ColB |
|Key | |密钥| Value |
价值|
|1 | | 1 | test |
测试
|2 | | 2 | test2 |
test2 |
|3 | | 3 | test4 |
test4 |
and I want to read these two columns into a dictionary. 我想将这两列读成字典。 I currently have this working but can't figure out how to extract out each key value pair
我目前有这项工作,但无法弄清楚如何提取每个键值对
sh = wb.sheet_by_index(0)
for rownum in range(sh.nrows):
print sh.row_values(rownum)
You're very close. 你很亲密 If you want to build a dictionary from the a sheet that only contains keys and values, in the first two columns, you can simply do
如果要从仅包含键和值的工作表中构建字典,请在前两列中进行
print dict(sh.row_values(rownum) for rownum in range(sh.nrows))
As John Y mentioned, if you need to extract two specific columns with indexes i (keys) and j (values), you can do instead: 如John Y所述,如果您需要提取两个具有索引i(键)和j(值)的特定列,则可以改为:
print dict((sh.cell_value(rownum, i), sh.cell_value(rownum, j)) for rownum in range(sh.nrows))
The key point is that dict()
can build a dictionary from an iterable of (key, value) tuples. 关键是
dict()
可以从(键,值)元组的可迭代元组构建字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.