I have a dictionary with 2000 items which looks like this:
JavaScript
x
2
1
d = {'10071353': (0, 0), '06030011': (6, 0), '06030016': (2, 10), }
2
Given that I want to write it to an .xlsx
file, I use this code (taken from here):
JavaScript
1
15
15
1
import xlsxwriter
2
workbook = xlsxwriter.Workbook('myfile.xlsx')
3
worksheet = workbook.add_worksheet()
4
row = 0
5
col = 0
6
order=sorted(d.keys())
7
for key in order:
8
row += 1
9
worksheet.write(row, col, key)
10
for item in d[key]:
11
worksheet.write(row, col + 1, item)
12
row += 1
13
14
workbook.close()
15
This produces an .xlsx
file with the following alignment:
JavaScript
1
10
10
1
A B
2
06030001 0
3
10
4
5
06030002 10
6
10
7
8
06030003 5
9
10
10
However, this is the alignment I am after:
JavaScript
1
7
1
A B C
2
06030001 0 10
3
4
06030002 10 10
5
6
06030003 5 10
7
What should I change in the script to achieve this?
Advertisement
Answer
This is what I think should help:
JavaScript
1
29
29
1
import xlsxwriter
2
workbook = xlsxwriter.Workbook('myfile.xlsx')
3
worksheet = workbook.add_worksheet()
4
row = 0
5
col = 0
6
7
order=sorted(d.keys())
8
for key in order:
9
row += 1
10
worksheet.write(row, col, key)
11
i =1
12
for item in d[key]:
13
worksheet.write(row, col + i, item)
14
i += 1
15
16
workbook.close()
17
18
IN:
19
20
d={'10071353':(0, 0),'06030011':(6, 0),'06030016':(2, 10)
21
22
OUT:
23
A B C
24
06030001 6 0
25
26
06030002 2 10
27
28
06030003 0 0
29