How do I write lists into CSV in python?
<p>I have the following list in Python. </p>

<pre><code>[('a1',
[('b', 1),
 ('c', 2),
 ('d', 3),
 ('e', 4),
 ('f', 5),
 ('g', 6]),

('a2',
[('c', 7),
 ('f', 8),
 ('g', 9),
 ('b', 1),
 ('e', 2),
 ('d', 3)])]
</code></pre>

<p>I would like to save the list as the following format in csv: </p>

<pre><code>a1      a2
b  1    c  7
c  2    f  8
d  3    g  9
e  4    b  1
f  5    e  2
g  6    d  3
</code></pre>

<p>The csv format is quite simple.</p>

<p>To start to know how to that, just create a csv file with the output you want, and open it with any text editor, you will obtain:</p>

<pre><code>a1,,a2,
b,1,c,7
c,2,f,8
d,3,g,9
e,4,b,1
f,5,e,2
g,6,d,3
</code></pre>

<p>So here is the code you need, but should have at least to obtain alone.</p>

<pre><code>input_list = [('a1', [('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)]), ('a2', [('c', 7), ('f', 8), ('g', 9), ('b', 1), ('e', 2), ('d', 3)])]

with open("my_file.csv", 'w') as f:
    first_line = [x[0] + ',' for x in input_list]
    f.write(",".join(first_line) + "\n")
    for x,y in zip(input_list[0][1], input_list[1][1]):
         k1, v1 = x
         k2, v2 = y
         f.write("{k1},{v1},{k2},{v2}\n".format(k1=k1, v1=v1, k2=k2, v2=v2))
</code></pre>

<p>An other solution is to use the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">csv module</a>. And there are some examples in the doc.</p>

python csv