Python openpyxl从excel获取值并存储在键值对中
已经编写了一个python脚本,该脚本获取单元格值并逐行显示在列表中 这是我的剧本:Python openpyxl从excel获取值并存储在键值对中,python,excel,python-2.7,openpyxl,Python,Excel,Python 2.7,Openpyxl,已经编写了一个python脚本,该脚本获取单元格值并逐行显示在列表中 这是我的剧本: book = openpyxl.load_workbook(excel_file_name) active = book.get_sheet_by_name(excel_file_name) def iter_rows(active): for row in active.iter_rows(): yield [cell.value for cell in row]
book = openpyxl.load_workbook(excel_file_name)
active = book.get_sheet_by_name(excel_file_name)
def iter_rows(active):
for row in active.iter_rows():
yield [cell.value for cell in row]
res = list(iter_rows(active))
for new in res:
print new
上述脚本的输出:[州、国家、代码][abc、xyz、,
0][def,lmn,0]
我想要以下格式的输出:[州:abc,国家:xyz,
代码:0][州:def,国家:lmn,代码:0]
请注意:我想从openpyxl执行此操作,请尝试以下操作:
res = iter_rows(active)
keys = next(res)
for new in res:
print dict(zip(keys, new))
res
是一个迭代器。因此,next(res)
给出下一个元素。在我们的例子中,是字典的钥匙。使用for
循环迭代res
的其余部分,dict()
为所有字典使用相同的键为每个元素new
创建一个新字典。函数zip()
以这样的方式组合两个(或多个)序列,即从每个序列中创建一个元素对dict()
使用其中一对作为一个新项的键和值,并遍历所有对。例如,这:
dict(zip('abc', [1, 2, 3]))
本词典中的结果:
{'a': 1, 'b': 2, 'c': 3}
对不起,重复了。因为我上一个问题的格式不好。添加一个与工作表方法同名的生成器似乎是代码不必要的复杂化。您可能希望提取第一行以获取密钥,然后按照@mike muller的建议使用zip。谢谢mike muller!这对我很管用。请你说说逻辑!再次感谢!现在这个例子已经很清楚了。