Python 在excel文件中写入字典值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23113231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write dictionary values in an excel file
提问by user3541631
I have a dictionary with multiple values for each key. I add the values using the following code:
我有一个字典,每个键都有多个值。我使用以下代码添加值:
d.setdefault(key, []).append(values)
The key value correspondence looks like this:
键值对应关系如下所示:
a -el1,el2,el3
b -el1,el2
c -el1
I need to loop thru the dictionary and write in an excel file:
我需要遍历字典并写入一个 excel 文件:
Column 1 Column 2
a el1
el2
el3
b el1
el2
c el1
For writing in the excel file I use xlsxwriter. I need help looping separately thru the dictionary, because after writing the key and I don't need to write it again until I finish all the corresponding values.
为了写入 excel 文件,我使用 xlsxwriter。我需要帮助通过字典单独循环,因为在写入密钥之后,在完成所有相应的值之前我不需要再次写入它。
采纳答案by carlosdc
It seems like you want something like this:
看起来你想要这样的东西:
import xlsxwriter
workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
d = {'a':['e1','e2','e3'], 'b':['e1','e2'], 'c':['e1']}
row = 0
col = 0
for key in d.keys():
row += 1
worksheet.write(row, col, key)
for item in d[key]:
worksheet.write(row, col + 1, item)
row += 1
workbook.close()