Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - Write dictionary values in an excel file

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:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...