How to dump a dictionary into an .xlsx file with proper column alignment?
<p>I have a dictionary with 2000 items which looks like this:</p>

<pre><code>d = {'10071353': (0, 0), '06030011': (6, 0), '06030016': (2, 10), ...}
</code></pre>

<p>Given that I want to write it to an <code>.xlsx</code> file, I use this code (taken from <a href="http://stackoverflow.com/questions/23113231/python-write-dictionary-values-in-an-excel-file?answertab=active#tab-top">here</a>):</p>

<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('myfile.xlsx')
worksheet = workbook.add_worksheet()
row = 0
col = 0
order=sorted(d.keys())
for key in order:
    row += 1
    worksheet.write(row, col,     key)
    for item in d[key]:
        worksheet.write(row, col + 1, item)
        row += 1

workbook.close()
</code></pre>

<p>This produces an <code>.xlsx</code> file with the following alignment:</p>

<pre class="lang-none prettyprint-override"><code>    A           B
    06030001    0
                10

    06030002    10
                10

    06030003    5
                10
</code></pre>

<p>However, this is the alignment I am after:</p>

<pre class="lang-none prettyprint-override"><code>A           B    C
06030001    0    10

06030002    10   10

06030003    5    10
</code></pre>

<p><strong>What should I change in the script to achieve this?</strong></p>

<p>The best way is to use <code>pandas</code> for this task. Some documentation is available here (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html</a> )</p>

<pre><code>import pandas as pd


a = {'1':[1,2,3,4], '2':[5,6,7,8]}
a = pd.DataFrame(a)


writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
a.to_excel(writer, sheet_name='Sheet1')
writer.save()
</code></pre>

<p>You may need to install <code>xlsxwriter</code> package</p>

python excel dictionary xlsxwriter